Android ImageAdapter 设置图像资源

标签 android imageview

下面是我的代码。我正在尝试将我的 SD 卡中的图像检索到 GridView 中。我的代码有问题。我不知道如何将图像设置到我的 ImageView 中。我的 ImageAdapter 中出现错误“ImageView 类型中的方法 setImageResource(int) 不适用于参数 (String)”

public class GridViewActivity extends Activity {
    private String[] mFileStrings;
    private File[] listFile;
    GridView grid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set title for the GridView
        setTitle("GridView");
        setContentView(R.layout.grid_view);

        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + "Tutorial");

        if (file.isDirectory()) {
            listFile = file.listFiles();
            mFileStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                mFileStrings[i] = listFile[i].getAbsolutePath();
            }
        }

        grid = (GridView) findViewById(R.id.gridview);

        grid.setAdapter(new ImageAdapter(this, mFileStrings));
    }

图像适配器

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private String[] data;
    public ImageAdapter(Context c, String[] d) {
        mContext = c;
        data=d;
    }

    public int getCount() {
        return data.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    // Create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // If it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(data[position]); //The method setImageResource(int) in the type ImageView is not applicable for the arguments (String)
        return imageView;
    }


}

我的编辑

 public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = (ImageView) convertView;
        }

        File imgFile = new File("" + data[position]);
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        imageView.setImageBitmap(myBitmap);
        return imageView;

    }

洛卡特:

04-12 14:18:59.811: E/AndroidRuntime(27379): FATAL EXCEPTION: main
04-12 14:18:59.811: E/AndroidRuntime(27379): java.lang.OutOfMemoryError
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:389)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:418)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at com.androidbegin.gridview.ImageAdapter.getView(ImageAdapter.java:46)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.AbsListView.obtainView(AbsListView.java:2201)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.GridView.onMeasure(GridView.java:1026)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.View.measure(View.java:12892)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.View.measure(View.java:12892)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:812)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.View.measure(View.java:12892)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2265)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.View.measure(View.java:12892)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1624)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2628)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.os.Looper.loop(Looper.java:137)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at android.app.ActivityThread.main(ActivityThread.java:4507)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invokeNative(Native Method)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invoke(Method.java:511)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
04-12 14:18:59.811: E/AndroidRuntime(27379):    at dalvik.system.NativeStart.main(Native Method)

最佳答案

您正在设置 imageView.setImageResource(data[position]) ,其中数据是字符串数组。 您需要将文件路径解码为位图,然后将其设置为 ImageView 。

在你的getView()

File imgFile = new  File(""+data[position]);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);

编辑:

您还可以使用 LazyList 或 Universal Image Loader 来显示 SD 卡中的图像。 What's LazyList? . Lazy List 确实按比例缩小以减少内存消耗。 Universal Image Loader 的工作原理与 LazyList 相同,但它有更多的配置选项。

https://github.com/thest1/LazyList .

https://github.com/nostra13/Android-Universal-Image-Loader

  //decodes image and scales it to reduce memory consumption
  private Bitmap decodeFile(File f){
     try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        BitmapFactory.Options o2 = new   BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
   } catch (FileNotFoundException e) {}
    return null;
}

如果位图太大,您需要缩放它们,然后在 ImageView 中显示相同的图像。此外,您还应该使用 view holder 来实现流畅的滚动和性能。您应该在不使用时回收位图。 gridview 中的可见 View 不会被回收。您可以使用 LazyList 或 Universal Image Loader。

http://developer.android.com/training/improving-layouts/smooth-scrolling.html .

http://www.youtube.com/watch?v=wDBM6wVEO70 .谈话是关于 viewholder 和 ListView 的性能。这同样适用于 gridview。

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html .高效加载位图。

如果遇到内存泄漏,请使用 MAT Analyzer 查找并修复问题。 http://www.youtube.com/watch?v=_CruQY55HOk .

关于Android ImageAdapter 设置图像资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15964160/

相关文章:

android - ImageView adjustViewBounds 好像不行??(不同项目不同结果)

android - 在 Android 中使用缩放查看并在 Canvas 上画线

android - RecyclerView 仅在屏幕上显示一项

android - 如何使用Gradle绕过登录屏幕

android - 使用 cURL 和 native Android NDK 的简单名称/内容多部分/表单数据 http 发布导致 CURLE_BAD_FUNCTION_ARGUMENT

java - 单击按钮后获取文本 android

java - 使用Picasso通过DataObject在RecyclerView中加载图像

android - 如何制作星形和圆形等自定义形状的图像?

java - 在多个 View 持有者 recyclerview 上转换异常

android - 如何禁用/管理 ImageView 上的辅助功能公告?安卓