Well I wanted to try out gallery in android and finally I
got time and little idea to do it. In this post I have created a gallery which
will display 3 images and you can scroll through it.
Create a new project and open res folder and add images
which want to display in the app into this folder. Once you are done open the
main.xml file and drag the gallery control onto the screen area. Then you need
to create resource called styleable which will be applied to each item of the
gallery.
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<declare-styleable name="GalleryTheme">
<attr name="android:galleryItemBackground"
/>
</declare-styleable>
</resources>
Then create a new class where you will define the images and
bind to the gallery. We will extend BaseAdapter since we need adapter to hold
all the images. Now create an array which has the names of the all the images
which need to be displayed as shown below.
Integer
images[]={R.drawable.ferrari,R.drawable.manutd,R.drawable.rcb};
Then create a constructor which takes the context into
consideration. Then define the style for the images as shown below.
public MyImageGallery(Context ctx){
context=ctx;
TypedArray ta =
ctx.obtainStyledAttributes(R.styleable.GalleryTheme);
galleryItem=ta.getResourceId(galleryItem,
R.styleable.GalleryTheme_android_galleryItemBackground);
ta.recycle();
}
When you extend the BaseAdapter the eclipse will give u
warning saying you need to implement 4 methods
1) getCount() – to get the number of items in the array.
public int getCount() {
return images.length;
}
2) getItem(int pos) – to get the particular item at the
position as specified.
@Override
public
Object getItem(int pos) {
return
pos;
}
3) getItemId(int pos) - to obtain the Id of the item at the position
specified.
public long getItemId(int pos) {
return pos;
}
4) getView() – where you define the properties related to
the image.
@Override
public
View getView(int arg0, View view, ViewGroup vg) {
ImageView
iv=new ImageView(context);
iv.setImageResource(images[arg0]);
iv.setLayoutParams(new
Gallery.LayoutParams(500, 500));
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setBackgroundResource(galleryItem);
return
iv;
}
The final code will look as shown in the screenshot given
below.
Now that we are done creating the adapter for the images, go
back to the main java file and create a new Gallery and start the above class
which will define all the images as shown in the code below
Gallery gly=(Gallery) findViewById(R.id.gallery1);
gly.setAdapter(new MyImageGallery(this));
The main java file will look as shown below.
Now run the project and the result is as shown below when
you scroll through the gallery.
No comments:
Post a Comment