For this the layout xml in this case, the main.xml will have a ‘Gallery’ element as shown below:
<Gallery
android:id="@+id/Gallery01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Gallery>
<ImageView android:id="@+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
It also has an ImageView element which is used to show the selected Image in a larger ImageView. Here is how it would look when executed.
I create an array of these resources/images in my activity with the following code:
Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};
As we have seen with all the other views so far, we need to have an adapter that associates the view with the data. Here the view is Gallery and the data is the above mentioned 10 images. An Adapter plays the role of linking the two as shown below:
Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
However, we do not have a readymade implementation of the ImageAdapter. We have to create our own implementation of the same by extending the BaseAdapter class. This is the core of the code in this example. The moment we extend the BaseAdapter, we have to override 4 methods. They are getCount(), getItem(), getItemId() and getView().
Before we go to each of them, let us see the constructor of the ImageAdpater:
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
…
}
It takes the context that is passed to the constructor. We need to examine this code a little. First, we can define our own resources or attributes in an XML file. Those attributes can be retrieved through the method obtainStyledAttributes. This is a method on the Context object. The returned value needs to be stored in a TypedArray object. A TypedArray is nothing but a container for an array of values that are returned by obtainStyledAttributes.
So, in my example, I have created an xml file by name attributes.xml in the res/values folder with the following content:
<resources>
<declare-styleable name="Gallery1">
<attr name="android:galleryItemBackground"/>
</declare-styleable>
</resources>
Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to say what should be the background of our images. For that we are using a pre-defined backgournd in R.attr class as galleryItemBackground.
So, this is accessed in the ImageAdapter contructor through the line
ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
The number 1 is to say that it is the first element in the attributes.xml file under the styelable Gallery1.
The rest of the over ridden methods are simple:
@Override
public int getCount() {
return pics.length;
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
iv.setImageResource(pics[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150,120));
iv.setBackgroundResource(imageBackground);
return iv;
}
The getView actually returns a View object when called. Here I have overridden it to return a ImageView object with the selected image inside it alosn with some scale, layout paramaters and the image background set.
Finally in the onCreate() method of the activity I have captured the onClick event on a Gallery item and within that I have toasted a message as well as displayed the image in a bigger manner below the gallery:
ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + " of Antartica",
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
That is it. You may download the complete code from here.
I am sorry, I just cannot figure out what you are trying to achieve with "R.styleable.Gallery1"
ReplyDeleteI assume you are loading some kind of background for the gallery. Is it not possible to do the same thing by loading "@android:drawable/galleryItemBackground" manually?
Hi Sai !
ReplyDeleteThis is Mohan. Your tutorial is very much helpful and easy to understand.
I have a doubt regarding "remote DataBase Connectivity". Assuming that I am having a database that stores some student details in a remote server. I want to access that Data Base from my Android for a query. Can you Plz give me some code to demonstrate this issue with a good example ? I will be waiting for your reply.
-Thanks in Advance.
Thanks for the tutorial. Is it possible to show how to save the images in the gallery as wallpapers?
ReplyDeleteworking code for gallery
ReplyDeletehttp://www.androidpeople.com/android-gallery-imageview-example/
Hai Sai,
ReplyDeleteI would like to know to create a curved Gallery, means the thumbnails will be arranged along a curved path.
All ideas are welcome
Thanks,
Sen
Hi, How to align the first item to the left???
ReplyDeletethanks
Thanks for this tutorial is working perfectly.
ReplyDeleteI was wondering if the code could be amended to read images from a specific folder on the sd card.
Thanks
Hi di,
ReplyDeleteNice one.If want to some spaces between images .How can we handle this.
pls suggest me.
ga.setSpacing(1);
Deletehi
ReplyDeletei tried as told in the tutorial but i am not getting the images whats wrong with me
actually i dont understand which method or the class you are going to use to display the images as a large image below the gallery.
ReplyDeleteactually i lost the image view below the gallery what i got wrong
ReplyDeleteis there a way to implement the above code with images from a database.
ReplyDeletepackage com.in.li;
ReplyDeleteimport android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;
import android.view.View;
public class Galry extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(Galry.this, "" + position, Toast.LENGTH_SHORT).show();
}
}
);
}
}
package com.in.li;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
Context mContext;
private Integer[] mImageIds = {
R.drawable.img1,
R.drawable.img1,
R.drawable.icon,
R.drawable.icon,
R.drawable.img1,
R.drawable.img1,
R.drawable.icon
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
private TypedArray obtainStyledAttributes(int[] hellogallery) {
// TODO Auto-generated method stub
return null;
}
public int getCount() {
return mImageIds.length;
}
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.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
/res/values
i m unable 2 find error..please help me.
res/values
ReplyDeleteHello,
ReplyDeleteCan anybody plz tell me how to show the image on the message body of email where image is on another view uploaded from photo gallery.
Plz reply as soon as possible.
Hello,
ReplyDeleteI am new to the android. your examples are very much helpfull to me..
Thank you
Hello Sai,
ReplyDeleteHow would you display the image if the array pics[] were inside the class ImageAdapter()?
Especially, what would you pass as the context when you initialize the instance of ImageAdapter?
Thanks,
hi Guys
ReplyDeleteif we swipe the gallery the images runs like anything.can u pls tell me is there any attribute or any way to show only one image per swipe. Please help me put... :(
Hello, your post is very good. And I has a infinite loop gallery, you can check here: Android Infinite Loop Gallery
ReplyDeletehii guys,
ReplyDeletei want ask one question, how to change frame background gallery?
Hi guyes,
ReplyDeleteI this tutorial is good, but images are statically defined can please anybody give a example for load all images from SDCard. so long time i am wondering for this but i can't find yet
Hi,
ReplyDeleteThis Example is very nice and very informative..I have small query can anyone help me on this...The query is is it possible to add on more text view and image on top of this or inside this gallery section()...Please help me....
Excellent continuation of the little information on the Android Developers website. It is a perfect explanation of the basics. Thanks!
ReplyDeletehi,
ReplyDeleteplease visit this implementation of gallery view:
http://themobilesource.blogspot.com/2011/05/creating-galleryview-with-code.html
thank you sai!
This comment has been removed by the author.
ReplyDeletehi,
ReplyDeletei want dis to display in grid format.. is dis possible.. anyone pl temme.
really good example. does it exist withot r.styleable?
ReplyDeletehi
ReplyDeleteI am calling this methosd ga.setSelection(1); in your onCreate method.after running your application first image is focused but i want focused image and also display the same time.Can anybody plz tell me how to show display the image
Thanks
Raj.
how to add zoom functionality in galleryview
ReplyDeleteNice example............helpful to new bies like me
ReplyDeletegood example, i am actually going to use your implementation.
ReplyDeletequick question though, how can you auto load the image when you scroll through the gallery thumbnails.
the current code requires you to click on the image. i would the thumbnail that is in the middle load the image
scusate ma è possibile passare immagini tra activity? ovvero una volta selezionata l'immagine dalla gallery è possibile " passarla" ad un altra activity?
ReplyDeleteHow to show image in full view with zoom & pinch ...?
ReplyDeleteHi really good example..... I want to add images from database to Gallery....can any one reply
ReplyDeleteThank you very much
Hi how to align the first image of the gallery to left by default while setselection not aligning exactly at leftside
ReplyDeleteHi Sai..
ReplyDeleteUr tutorials are really nice..
My task is that i'm getting images from remote server..
How can i use the same concept to do that..
Please help me out with this...
Regards,
Mounika M V
how to remove an item from gallery?
ReplyDeleteHIIII...Your tutorials really awesome .I am getting a problem in Gallery view because in your tutorial it is static when i am working in dynamic way that is rendering images from server how can i get images to Gallery ... from server their are string values when we call the image i need to use the string not int values for that what i need to do how can i change the string values to int values to render the images from server ?????if u know pls share it ...
ReplyDeleteThks in advance....
do you find solution? if yes please share it..
DeleteThank you
This comment has been removed by the author.
ReplyDeletehow to set picture scrolling panel bottom?
ReplyDeletehi iam an android developer. i need a simple help from u. iam using grid view to display a set of images. My requirement is after clicking any one of the image it should navigate to another activity which is a gallery view and the image in the gallery view should start from the image which i click in previous activity. for eg i clicked 5th image and in next activity it should start from that image and should be scrollable to and fro. plzzzz help...my email shukur.shariq@gmail.com
ReplyDeletethanks its nice tutorial,it exactly same that i am searching for......
ReplyDeletekoothi
ReplyDeletei have achieved the above gallery view but i want to 3D gallery like in android phone gallery
ReplyDeletetnk u very much!!!!!!!!
ReplyDeleteworked fr me
Thanks... It is of great help
ReplyDeleteTHANKS A LOT DUDE! YOU HELPED ME A LOT!
ReplyDeleteimage from sdcard
ReplyDeleteThanks..It is very useful...
ReplyDeletenice
ReplyDeleteReally Short n quick under standing tutorials
ReplyDeleteThank you very much for this tutorial. It really helped me. - Santosh
ReplyDeleteNice Tutorial
ReplyDeletesend project to mail
ReplyDeletethx a lot
hi
ReplyDeleteany one can help me to how to develop the gallery widget in android
that will shows the all the images in the phone.
send to my mail
rajareddy12android@gmail.com
Hi,
ReplyDeleteLike image gallery,can we put video gallery like this for giving R.drawable image like that,we can give lots of url like that,is it possible?
send me the details
karthickbe2008@gmail.com
Hello,
ReplyDeletehow to add this project for view image from my site with webview?
Regards
Hi
ReplyDeleteHow can i set image switcher gallery in vertical view...
Can any one help..?
Hi
ReplyDeletehow can add image with the background image and saved to the image gallery. Is it possible to do so..? If could you help me how it can be add..?
How to change border for images?
ReplyDeletei want gallery view as it is scrolling automatically... can anyone help me..??????
ReplyDelete