我正在寻找有关如何执行此操作的一些建议。
我想要一个 Activity ,用户可以从 Android 图库中进行选择,然后图像将被添加到 Activity 的 GridView 中。我已经成功地分别实现了两者,但是当我必须将它们结合起来时,我不知所措。 GridView 教程是here 。问题是 GridView 教程使用来自 res/drawable 的图像,因此我从画廊获得的 uri 并不完全有效。
我应该如何在ImageAdapter类中设置图像?我一直在尝试使用手机中一张图像的 uri 地址执行 imageView.setImageBitmap(bitmap),但它不起作用。
我正在考虑创建一个 String ArrayList,其中包含从图库获取的图像的 uri。这样我就可以轻松地添加、删除和存储图像。
随之而来的其他问题是,如果我显示图像,如果我再次调用 setAdapter ,它会刷新吗?如果我从源ArrayList中删除,会自动删除工作吗?
谢谢
以下是我编辑的 GridView 中的代码:
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;
}
}
最佳答案
回答第一部分:如果您的测试包含您选择的图像的Uri,只需使用imageView.setImageURI(targetUri)
.
回答第二部分:要刷新 GridView,只需调用 mGridView.invalidateViews()
,整个 GridView 将被重新绘制,因此发生的任何更改您的来源将反射(reflect)在这里。无需再次调用 setAdapter()。当您第一次绘制网格时,setAdapter() 最初只会被调用一次。之后,只需 invalidateViews() 即可刷新它。
关于android - 从android图库获取图像并放入gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12134182/