【问题标题】:Obtaining image from android gallery and put in gridview从android画廊获取图像并放入gridview
【发布时间】:2012-08-26 21:48:28
【问题描述】:

我正在寻找有关如何执行此操作的建议。

我想要一个用户从 android 库中选择的活动,然后图像将添加到活动的网格视图中。我已经成功地分别实现了两者,但是当我必须将它们结合起来时,我不知所措。网格视图教程是here。问题是网格视图教程使用来自 res/drawable 的图像,所以我从画廊获得的 uri 并不完全有效。

我应该如何在 ImageAdapter 类中设置图像?我一直在尝试使用手机中一张图像的 uri 地址来执行 imageView.setImageBitmap(bitmap),但没有成功。

我正在考虑创建一个 String 的 ArrayList,其中包含从图库中获取的图像的 uri。这样我就可以轻松地添加、删除和存储图像。

与此相关的其他问题是,如果我显示图像,如果我再次调用 setAdapter,它会刷新吗?如果我从源 ArrayList 中删除,会自动删除工作吗?

谢谢

以下是我编辑的网格视图中的代码:

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return imageId.size();
    }

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

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

    // 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.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }


        Uri targetUri = Uri.parse(tests.get(0));
        //tests contains the uri of the photo i'm trying to import from my phone gallery in string form
        Bitmap bitmap;
        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
        imageView.setImageBitmap(bitmap);

        return imageView;
    }
}

【问题讨论】:

  • GridView 不限于可绘制文件夹中的图像。您可以在 GridView 中显示任何图像。
  • 我意识到了,但我应该怎么做呢? setImageBitmap 应该可以工作,但不知道为什么没有。如果我这样做,我也更担心刷新是否会起作用。
  • 在我看到你一直在使用的代码之前,我无法告诉你出了什么问题。
  • 您是否尝试过使用我在回答中提到的 setImageUri() ?

标签: android gridview image-gallery


【解决方案1】:

第一部分的答案:如果您的测试包含您选择的图像的Uri,只需使用imageView.setImageURI(targetUri)

第二部分的答案:要刷新 GridView,只需调用 mGridView.invalidateViews(),您的整个 GridView 将被重绘,因此您的源代码中发生的任何更改都会在此处反映。无需再次调用 setAdapter()。当您第一次绘制网格时,setAdapter() 最初只会被调用一次。之后,只需 invalidateViews() 即可刷新它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多