I’m looking for some advice on how to do this.
I want to have an activity where the user select from android gallery, then the image will be added into a grid view on the activity. I have successfully implemented both separately, but when I have to combine them I’m at a loss. Grid View tutorial is here. Problem is that grid view tutorial uses images from res/drawable, so the uri i obtain from gallery doesn’t exactly work.
How should I set the image inside the ImageAdapter class? I’ve been trying to do imageView.setImageBitmap(bitmap) with the uri address of one of the images in my phone, but it didn’t work.
I’m thinking of creating an ArrayList of String that contains uri for the images obtained from the gallery. This way i can add, delete, and store the images with ease.
Other questions along with this is that if i get the images displayed, will it refresh if i simply call setAdapter again? would delete work automatically if i delete from the source ArrayList?
Thank you
The following is the code from grid view tut that i edited:
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;
}
}
Answer to the first part : If your tests contains the Uri of the image that you have selected, simply use
imageView.setImageURI(targetUri).Answer to second part : To refresh a GridView, just call
mGridView.invalidateViews()and your whole GridView will be redrawn and thus any changes that have taken place in your source would be reflected here. No need to call setAdapter() again. setAdapter() will be called only once initially, when you are drawing the grid for the first time. After that, just invalidateViews() to refresh it.