NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Tuesday, 18 May 2010

Gallery View | Android Developer Tutorial

Continuing on the Views, I have taken up the Gallery View that helps in showing Images as in a gallery. As per the android documentation, this is the definition: “A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.”


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.

Now, I create a GalleryView Activity. To view a set of images of Antartica, I have created small sized images of antartica and stored them in the res/drawable-ldpi folder starting form antartica1.png to antartica10.png.

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.

63 comments:

  1. I am sorry, I just cannot figure out what you are trying to achieve with "R.styleable.Gallery1"

    I 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?

    ReplyDelete
  2. Hi Sai !
    This 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.

    ReplyDelete
  3. Thanks for the tutorial. Is it possible to show how to save the images in the gallery as wallpapers?

    ReplyDelete
  4. working code for gallery

    http://www.androidpeople.com/android-gallery-imageview-example/

    ReplyDelete
  5. Hai Sai,
    I 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

    ReplyDelete
  6. Hi, How to align the first item to the left???

    thanks

    ReplyDelete
  7. Thanks for this tutorial is working perfectly.
    I was wondering if the code could be amended to read images from a specific folder on the sd card.

    Thanks

    ReplyDelete
  8. Hi di,

    Nice one.If want to some spaces between images .How can we handle this.


    pls suggest me.

    ReplyDelete
  9. hi
    i tried as told in the tutorial but i am not getting the images whats wrong with me

    ReplyDelete
  10. 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.

    ReplyDelete
  11. actually i lost the image view below the gallery what i got wrong

    ReplyDelete
  12. is there a way to implement the above code with images from a database.

    ReplyDelete
  13. package com.in.li;

    import 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.

    ReplyDelete
  14. Hello,
    Can 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.

    ReplyDelete
  15. Hello,
    I am new to the android. your examples are very much helpfull to me..
    Thank you

    ReplyDelete
  16. Hello Sai,

    How 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,

    ReplyDelete
  17. hi Guys

    if 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... :(

    ReplyDelete
  18. Hello, your post is very good. And I has a infinite loop gallery, you can check here: Android Infinite Loop Gallery

    ReplyDelete
  19. hii guys,
    i want ask one question, how to change frame background gallery?

    ReplyDelete
  20. Hi guyes,

    I 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

    ReplyDelete
  21. Hi,
    This 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....

    ReplyDelete
  22. Excellent continuation of the little information on the Android Developers website. It is a perfect explanation of the basics. Thanks!

    ReplyDelete
  23. hi,
    please visit this implementation of gallery view:
    http://themobilesource.blogspot.com/2011/05/creating-galleryview-with-code.html

    thank you sai!

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. hi,
    i want dis to display in grid format.. is dis possible.. anyone pl temme.

    ReplyDelete
  26. really good example. does it exist withot r.styleable?

    ReplyDelete
  27. hi
    I 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.

    ReplyDelete
  28. how to add zoom functionality in galleryview

    ReplyDelete
  29. Nice example............helpful to new bies like me

    ReplyDelete
  30. good example, i am actually going to use your implementation.

    quick 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

    ReplyDelete
  31. scusate ma è possibile passare immagini tra activity? ovvero una volta selezionata l'immagine dalla gallery è possibile " passarla" ad un altra activity?

    ReplyDelete
  32. How to show image in full view with zoom & pinch ...?

    ReplyDelete
  33. Hi really good example..... I want to add images from database to Gallery....can any one reply

    Thank you very much

    ReplyDelete
  34. Hi how to align the first image of the gallery to left by default while setselection not aligning exactly at leftside

    ReplyDelete
  35. Hi Sai..
    Ur 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

    ReplyDelete
  36. how to remove an item from gallery?

    ReplyDelete
  37. HIIII...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 ...

    Thks in advance....

    ReplyDelete
    Replies
    1. do you find solution? if yes please share it..

      Thank you

      Delete
  38. This comment has been removed by the author.

    ReplyDelete
  39. how to set picture scrolling panel bottom?

    ReplyDelete
  40. hi 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

    ReplyDelete
  41. thanks its nice tutorial,it exactly same that i am searching for......

    ReplyDelete
  42. i have achieved the above gallery view but i want to 3D gallery like in android phone gallery

    ReplyDelete
  43. tnk u very much!!!!!!!!
    worked fr me

    ReplyDelete
  44. Thanks... It is of great help

    ReplyDelete
  45. THANKS A LOT DUDE! YOU HELPED ME A LOT!

    ReplyDelete
  46. Really Short n quick under standing tutorials

    ReplyDelete
  47. Thank you very much for this tutorial. It really helped me. - Santosh

    ReplyDelete
  48. Nice Tutorial

    ReplyDelete
  49. send project to mail
    thx a lot

    ReplyDelete
  50. hi
    any 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

    ReplyDelete
  51. Hi,
    Like 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

    ReplyDelete
  52. Hello,
    how to add this project for view image from my site with webview?

    Regards

    ReplyDelete
  53. Hi

    How can i set image switcher gallery in vertical view...
    Can any one help..?

    ReplyDelete
  54. Hi
    how 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..?

    ReplyDelete
  55. How to change border for images?

    ReplyDelete
  56. i want gallery view as it is scrolling automatically... can anyone help me..??????

    ReplyDelete