Sunday 28 March 2010

Gallery Example

Often we need in Android to make a view which contains all the images in a row and we can browse them by sliding them....Gallery is the control in android for this....

First of all you will have to make an inner class which extends BaseAdapter. Here's the code

public class ImageAdapter extends BaseAdapter {

       
        int mGalleryItemBackground;
        private Context mContext;

        private int[] mImageIds = {
                R.drawable.icon,R.drawable.android,R.drawable.array_03
        };


        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.default_gallery_android_galleryItemBackground ,mImageIds);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.default_gallery_android_galleryItemBackground, 0);
            a.recycle();
        }

        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;
        }
}

Now the Activity class should look like this...

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(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
}


In your xml code you will just have to add these lines...

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>

At the end your program will look like this