Search This Blog

Monday, February 13, 2012

Gallery, Using Gallery widget

Here is a exercise to implement a picture view using Gallery, a view that shows items in a center-locked, horizontally scrolling list.
Basically, this exercise follow the Android Tutorial, Hello Gallery.Create a Android Application, HelloGallery. 

Copy some images, in .png format, into res/drawable/ directory. Named a,b,...,e.png in my case.
Android supports bitmap resource files in a few different formats: png (preferred), jpg (acceptable), gif (discouraged). The bitmap file itself is compiled and referenced by the file name without the extension (so res/drawable/my_picture.png would be referenced as R.drawable.my_picture).

Create res/values/attrs.xml to define Theme_android_galleryItemBackground.

<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="Theme">
<attr name="android:galleryItemBackground" />

Modify main.xml to have a Gallery in the screen.

<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android=""

Now open the java file and insert the following code into it.

public class HellogalleryActivity extends Activity {

/** Called when the activity is first created. */


public void onCreate(Bundle savedInstanceState) {

   Gallery g = (Gallery) findViewById(;
   g.setAdapter(new ImageAdapter(this));

   g.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent,
           View v, int position, long id) {
           Toast.makeText(HellogalleryActivity.this, "" + position,

public class ImageAdapter extends BaseAdapter {
   int mGalleryItemBackground;
   private Context mContext;

   private Integer[] mImageIds = {

   public ImageAdapter(Context c) {
       mContext = c;
       TypedArray a = obtainStyledAttributes(R.styleable.Theme);
       mGalleryItemBackground = a.getResourceId(                  


   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.setLayoutParams(new Gallery.LayoutParams(150, 100));

       return i;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.