Hello, Views >

Hello, GridView

A GridView displays items in a two-dimensional, scrolling grid. The items are acquired from a ListAdapter.

  1. Start a new project/Activity called HelloGridView.
  2. Find some photos you'd like to use, or copy some from the SDK samples res/drawable/ folder of your project.
  3. Open the layout and make it like so:
    <?xml version="1.0" encoding="utf-8"?>
    <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@+id/gridview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:columnWidth="90dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
    />
    
  4. Open the HelloGridView Java file. Insert the following for the onCreate() method:
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
    }
    

    Here, we get a handle on our GridView, from the layout, and give it an Adapter. We're actually going to create our own Adapter called ImageAdapter.

  5. Create a new class (nested or otherwise), called ImageAdapter, which extends BaseAdapter:
    public class ImageAdapter extends BaseAdapter {
        private Context mContext;
    
        public ImageAdapter(Context c) {
            mContext = c;
        }
    
        public int getCount() {
            return mThumbIds.length;
        }
    
        public Object getItem(int position) {
            return null;
        }
    
        public long getItemId(int position) {
            return 0;
        }
    
        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            } else {
                imageView = (ImageView) convertView;
            }
    
            imageView.setImageResource(mThumbIds[position]);
            return imageView;
        }
    
        // references to our images
        private Integer[] mThumbIds = {
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7
        };
    }
    

    First we take care of some required methods inherited from BaseAdapter. The constructor and getCount() are self-explanitory. Normally, getItem() should return the actual object at the specified position in our Adapter, but for this Hello World, we're not going to bother. Likewise, getItemId() should return the row id of the item, but right now we don't care.

    However, getView() is the method we care about. This one creates a new View for each image that we put in our ImageAdapter. So we're going to create an ImageView each time. When this is called, we're going to receive a View, which is likely a recycled View object (at least after the first call), so we check for this—if it's null, we initialize the ImageView and setup all the properties we want. The LayoutParams() initialization sets the height and width of the View—this ensures that no matter the drawable size, each image is resized and cropped to fit in the ImageView (if necessary). With setScaleType(), we say that images should be cropped toward the center (if necessary). And finally, we set the padding within the ImageView. (Note that, if the images have various aspect-ratios, as they do in this demo, then less padding will cause for more cropping of the image, if it does not match the dimensions given to the ImageView.) At the end of getView() we set the image resource and return the ImageView.

    All that's left is our array or drawable resources at the bottom.

  6. Run it.

Your grid layout should look something like this:

Try experimenting with the behaviors of the GridView and ImageView by adjusting their properties. For example, instead of setting the ImageView LayoutParams, you can try using setAdjustViewBounds(boolean).

References