Learn Android Development For Beginners

GridView

The GridView control displays a list of items in two dimensional (Rows and Columns) scrollable grid. Same as ListView the adapter is responsible to provide items to the GridView. An adapter is the bridge between UI component and the data.

GridView

Create a new project and in the activity layout file add the GridView control and set its required properties.

 <GridView android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/gridView"
            android:horizontalspacing="10dp"
            android:verticalspacing="10dp"
            android:columnwidth="100dp"
            android:numcolumns="auto_fit" />

The grid view has some important properties that need to be understand

  • android:numColumns: It defines how many columns the grid shows. It’s values can be “auto_fit” or any number e.g. 1, 2, 3, 4, 5 etc. The "auto_fit" sets number of columns according to width and columnWidth of the grid. If it has any number e.g. android:numColumns="3", it shows the fixed number of columns.
  • android:columnWidth: It defines the width of the column.
  • android:horizontalSpacing: it defines the horizontal spacing between the columns.
  • android:verticalSpacing: it defines the vertical spacing between the rows.

For setting the adapter of the GridView, go to the code file of the activity and set the adapter same as we set for the ListView Control.

final GridView gridView = (GridView) findViewById(R.id.gridView);
        
List<String> myList = new ArrayList<String>();


for(int i=1;i<=40;i++)
{
    myList.add("Item " + i);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, myList);


// Assign adapter to gridView
gridView.setAdapter(adapter);

Create the list of string and instance of the ArrayAdapter and set it using setAdapter() method of the GridView.

For registering click listener set item click listener using setOnItemClickListener method and in the onItemClick method write your required code.

 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
 
        String  itemValue    = (String) gridView.getItemAtPosition(i);
 
        // Show Message
        Toast.makeText(getApplicationContext(),
                "Position :" + i + "\r\nGrid Item : " + itemValue, Toast.LENGTH_LONG)
                .show();
 
    }
 
 });

i parameter passed in OnItemClick method is the position of the clicked item. Use getItemAtPosition method to get the value of clicked item.

Customize Grid View

The customization of the GridView is also similar to the ListView. The adapter is responsible to provide UI component for each data item to GridView. Simply extends the adapter to customize the grid.

Custom GridView

For customizing the grid view item, create new xml file in layout folder and name it grid_list_item.xml and write xml for the custom layout of grid item.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text" />
</LinearLayout>

Add new activity in the application and in the layout file of the activity add the grid view.

 <GridView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/myGridView"
    android:numColumns="3" />

Create a new CustomGridAdapter class. Extends it with BaseAdapter class and Override its required methods. See the code below.

public class CustomGridAdapter extends BaseAdapter {

    private Context _context;
    private int[] _imageList;
    private String[] _textList;

    public CustomGridAdapter(Context context, String[] textList, int[] imageList)
    {
        _context = context;
        _imageList = imageList;
        _textList = textList;
    }

    @Override
    public int getCount() {
        return (_textList == null)?0:  _textList.length;
    }

    @Override
    public Object getItem(int i) {
        return _textList[i];
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
    
        if (view == null) {
           
            LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.grid_list_item, viewGroup,false);
        }

        TextView textView = (TextView) view.findViewById(R.id.textView);
        ImageView imageView = (ImageView)view.findViewById(R.id.imageView);

        textView.setText(_textList[i]);
        imageView.setImageResource(_imageList[i]);

        return view;
    }
}

In the getView method create a view for grid item using LayoutInflater and assign the appropriate values to the controls inside the layout file.

In the code of the activity create the instance of the CustomGridAdapter class and assign it to grid using the setAdapter() method. See the code below

 int[] imageList = new int[45];
 String[] titleList = new String[45];
 
 for (int i = 0; i < 45; i++) {

    titleList[i] = "Title " + i;

    int imgID = 0;
    switch ((i % 4)) {
        case 0: {
            imgID = R.drawable.image1;
            break;
        }
        case 1: {
            imgID = R.drawable.image2;
            break;
        }
        case 2: {
            imgID = R.drawable.image3;
            break;
        }
        case 3: {
            imgID = R.drawable.image4;
            break;
        }
    }

    imageList[i] = imgID;
 }

 CustomGridAdapter adapter = new CustomGridAdapter(getApplicationContext(),titleList,imageList);

 final GridView grid = (GridView) findViewById(R.id.myGridView);
 grid.setAdapter(adapter);

Handling of the click event is almost same as it is described in previous example. See the code below

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
           
            String  itemValue = (String) grid.getItemAtPosition(i);
           
            // Show Message
            Toast.makeText(getApplicationContext(),
                    "Position :" + i + "\r\nGrid Item : " + itemValue, Toast.LENGTH_LONG)
                    .show();
        }

 });

Download Source Code

You can get the source code. Download Source Code

Other Topics

;