How to create Custom Grid View in Android
How to create Custom Grid View in Android

Yesterday I have written a post on Simple Grid View with single text view only. Now I am writing for the Custom Grid View having Image and Text View in each of its grid.

Adapter loads the Grid View with the data from data sources. For grid view with a single text, we used ArrayAdapter of String type. For a Grid View with more than one widgets, you need to create a Custom Adapter that is a user define Adapter that extends Predefined Adapter. Same concept I am going to use here.

  1. Create a new project File -> New -> New Project. Give a name as CustomGridView go next -> next and finish.
  2. Add some images in res-> drawable. you can simply paste any images or import default icons as File-> New-> Vector Assets -> Material Icon -> Choose-> select whichever you want and press Ok.
  3. Open activity_main.xml from res-> layout -> activity_main.xml and copy the code below in Text tab of activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0f0f0">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:columnWidth="110dp"
        android:drawSelectorOnTop="true"
        android:gravity="center"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        android:focusable="true"
        android:clickable="true"/>

</RelativeLayout>

4. Create a single grid layout as grid_item in res-> layout-> right click ->New -> Layout resource file give a name grid_item. Copy the below code in that file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="130dp"
    android:layout_height="130dp"
    android:orientation="vertical"
    android:background="#d7d2d2">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/gridImage"
        android:layout_gravity="center_horizontal|center_vertical"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:layout_marginTop="10dp"
        android:textSize="20dp"
        android:id="@+id/gridText"/>

</LinearLayout>

5. Now create a java file as GridCustomAdapter and copy the below code in it.

package com.buzzmycode.customgridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by SANA on 9/2/2016.
 */
public class GridCustomAdapter extends BaseAdapter {

    String[] gText = {};
    int[] gImage = {};
    Context context;

    GridCustomAdapter(Context context, String[] gTxt, int[] gImage){
        this.gText = gTxt;
        this.gImage = gImage;
        this.context = context;

    }

    @Override
    public int getCount()
    {
       return gText.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup){
        View grid;
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        if(view == null){

            grid = new View(context);
            grid = layoutInflater.inflate(R.layout.grid_item,null);
            TextView grid_business_name = (TextView) grid.findViewById(R.id.gridText);
            ImageView grid_business_image = (ImageView) grid.findViewById(R.id.gridImage);
            grid_business_name.setText(gText[i]);
            grid_business_image.setImageResource(gImage[i]);
        }
        else {
            grid = (View) view;
        }
        return grid;
    }
}

6.Now open your MainActivity.java and copy the code below.

package com.buzzmycode.customgridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    GridCustomAdapter adapter;
    String[] grid_array = {"Play",
            "Pause",
            "Fast Rewind",
            "Fast Forward",
            "Previous",
            "Next",
            "Volume Off",
            "Volume Down",
            "Volume Up"};

    int[] grid_image = {R.drawable.ic_play_arrow_black_24dp,
            R.drawable.ic_pause_black_24dp,
            R.drawable.ic_fast_rewind_black_24dp,
            R.drawable.ic_fast_forward_black_24dp,
            R.drawable.ic_skip_previous_black_24dp,
            R.drawable.ic_skip_next_black_24dp,
            R.drawable.ic_volume_off_black_24dp,
            R.drawable.ic_volume_down_black_24dp,
            R.drawable.ic_volume_up_black_24dp
         };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_grid);
        GridView gridView = (GridView) findViewById(R.id.gridView);

        adapter = new GridCustomAdapterClass(SimpleGridActivity.this,grid_array,grid_image);
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                String seleted_grid = ((TextView)view.findViewById(R.id.gridText)).getText().toString();
                Toast.makeText(SimpleGridActivity.this, "You select "+seleted_grid + " at position "+ i , Toast.LENGTH_LONG).show();
            }
        });


    }
}

7. Your AndroidManifest.xml will be as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.buzzmycode.customgridview">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

8. Finally, run your code,  You will have the following output.

How to create Custom Grid View in Android
How to create Custom Grid View in Android

Here we did with the Grid View with image and text in its grid in Android. Hope you found it easy and understand v. For any query comment below I will be there to solve your query.

Leave a Reply