Reputation: 2620
I just wanna display image gallery dynamically in android.(i.e) shouldn't get image from path res/drawable..
How could I do this?
Upvotes: 0
Views: 3102
Reputation: 1486
The Gallery documentation says:
This widget is no longer supported. Other horizontally scrolling widgets include HorizontalScrollView and ViewPager from the support library.
The best way for you is to use ViewPager with an ImageView in its fragment layout.
Upvotes: 1
Reputation: 13815
This is the code to initialize Gallery view ..
final Gallery g = (Gallery) findViewById(R.id.gallery);
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Toast.makeText(CurrentActivity.this, " " + position, Toast.LENGTH_SHORT).show();
}
});
g.setBackgroundColor(Color.LTGRAY);
g.setAdapter(new ImageAdapter(getApplicationContext()));
Now Images can be fetched from the URL . You just need to tell the image adapter to fetch image from URL while genarating the View of every item of gallery.
The following function is for fetching the image from any URL and returning the drawable that can be set as image view
Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
}
Make this ImageAdapter class as inner , check the code..
Fill A Vector data with URL of images
class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageDrawable(drawable_from_url(data.get(position), "src"));
i.setLayoutParams(new Gallery.LayoutParams(300, 180));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
Hope this will help :)
Upvotes: 2