Skip to main content

How To Create GridView In Android

http://devdeeds.com/how-to-create-gridview-in-android/





demo_gridview
Alternative design pattern to ListView. One of the ready made widget available in android UI widget set in which contents arranged like rows and columns(2D). Space conscious and eye catcher. Thus popular in mobile devices.
GridView is commonly seen in content arrangement where single item needs to be projected like in media galleries and Calendar.
Like a twin brother of ListViewGridview is very similar to ListView in many aspects. So if you have ever worked with any of these then other one can be easily understood with less effort.
Before we start we have a quick meeting with 3 very important parts of the GridView. These are the following

Step 1. Add Gridview To Layout

Open your layout XML file in design mode and drag and drop Gridview into layout. Now you have the layout to show GridView items. GridView is only a layout actually does not really care about the content but how they arrange in the layout.
Here you can define many attributes related to the layout like dimension, spacing, number of rows and columns etc.
Open res/layout/activity_flower.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".FlowerGalleryActivity">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2"
        android:verticalSpacing="@dimen/elementMargin"
        android:horizontalSpacing="@dimen/elementMargin"
        android:gravity="center"
        />
</RelativeLayout>

Step 2. Adapter Layout

Which is the connecter between GridView and DataSet and he has one more duty it is the definition of each item in the GridView.
Adapter is like a pipe connection where data are passed to GridView one after another. Each passing data forms a view. Adapter has a definition for this formation. Based on this definition views are drawn. Each item in the GridView has a position which is starting from 0 to n. Where n is the total number of items – 1
In future if you customize the GridView then this is the part where you working on more than anywhere else.
Open res/layout/adapter_flower.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"
    >

    <ImageView
        android:id="@+id/photoView"
        android:layout_width="@dimen/gridView_cellWidth"
        android:layout_height="@dimen/gridView_cellHeight"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop"
         />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="@dimen/elementMargin"
        android:background="@color/overlay"
        android:padding="@dimen/cellText_padding"
        android:textColor="@color/textColor"
        android:textSize="@dimen/cellText_textSize" />

</RelativeLayout>

Step 3. Create Dataset Class

Dataset is the collection of user defined item objects. Data Sources, which are responsible for providing data for GridView, may be different for each Application we If we have ‘n’ number of items present in GridView then Dataset will have ‘n’ number of item objects in it. Each item object has properties with values.
Flower.java
package gridview.devdeeds.com.gridview.dataset;

public class Flower {

    private String mFlowerName;
    private int mPhotoPath;

    public String getFlowerName() {
        return mFlowerName;
    }

    public void setFlowerName(String name) {
        mFlowerName = name;
    }

    public int getPhotoPath() {
        return mPhotoPath;
    }

    public void setPhotoPath(int photoPath) {
        mPhotoPath = photoPath;
    }

}

Step 4. Create FlowerAdapter Class

package gridview.devdeeds.com.gridview.adapter;

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;

import java.util.ArrayList;

import gridview.devdeeds.com.gridview.R;
import gridview.devdeeds.com.gridview.dataset.Flower;


//This is a custom adapter. It has been extended from BaseAdapter because
//we need to overrider the getView function for changing the layout of each Grid View Item
public class FlowerAdapter extends BaseAdapter {

    private ArrayList<Flower> mFlowerData = new ArrayList<>();
    private LayoutInflater mInflaterCatalogListItems;

    public FlowerAdapter(Context context, ArrayList<Flower> flowerData) {
        mFlowerData = flowerData;
        mInflaterCatalogListItems = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    //This function will determine how many items to be displayed
    @Override
    public int getCount() {
        return mFlowerData.size();
    }

    @Override
    public Object getItem(int position) {
        return mFlowerData.get(position);
    }

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

    //This function will iterate through each object in the Data Set. This function will form each item in a Grid View
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if (convertView == null) {

            holder = new ViewHolder();
            convertView = mInflaterCatalogListItems.inflate(R.layout.adapter_flower,
                    null);
            holder.sFlowerName = (TextView) convertView.findViewById(R.id.textView);
            holder.sFlowerPhotoPath = (ImageView) convertView.findViewById(R.id.photoView);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        //Change the content here
        if (mFlowerData.get(position) != null) {
            holder.sFlowerName.setText(mFlowerData.get(position).getFlowerName());
            holder.sFlowerPhotoPath.setImageResource(mFlowerData.get(position).getPhotoPath());
        }

        return convertView;
    }

    //View Holder class used for reusing the same inflated view. It will decrease the inflation overhead @getView
    private static class ViewHolder {
        TextView sFlowerName;
        ImageView sFlowerPhotoPath;

    }

}

Connection between these 3 parts

Now we have to connect them in order to make Gridview viewable. There is a order of connection. First connect dataset to adapter then after that connect adapter to Gridview. The below figure shows the internal working of a GridView.
gridview-adapter-dataset

Example

Below is the sample example showing the basic usage of GridView. In this example i will show you how to add contents to GridView, make changes to the content and update GridView after each change.

In Activity Class

FlowerGalleryActivity.java
package gridview.devdeeds.com.gridview;

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.Toast;

import java.util.ArrayList;

import gridview.devdeeds.com.gridview.adapter.FlowerAdapter;
import gridview.devdeeds.com.gridview.dataset.Flower;

public class FlowerGalleryActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    ArrayList<Flower> mFlowerDataSet = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //Prepare DataSet
        mFlowerDataSet = prepareDataSet();

        //Initialize Grid View for programming
        GridView gridview = (GridView) findViewById(R.id.gridView);

        //Connect DataSet to Adapter
        FlowerAdapter flowerAdapter = new FlowerAdapter(this, mFlowerDataSet);

        //Now Connect Adapter To GridView
        gridview.setAdapter(flowerAdapter);

        //Add Listener For Grid View Item Click
        gridview.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        //Show Name Of The Flower
        Toast.makeText(FlowerGalleryActivity.this, mFlowerDataSet.get(position).getFlowerName(),
                Toast.LENGTH_SHORT).show();
    }


    //Creating Data Set By Adding 6 flower objects
    private ArrayList<Flower> prepareDataSet() {

        ArrayList<Flower> flowerData = new ArrayList<>();

        Flower flower;

        //1st Item
        flower = new Flower();
        flower.setFlowerName("Alyssum");
        flower.setPhotoPath(R.drawable.alyssum);
        flowerData.add(flower);

        //2nd Item
        flower = new Flower();
        flower.setFlowerName("Daisy");
        flower.setPhotoPath(R.drawable.daisy);
        flowerData.add(flower);


        //3rd Item
        flower = new Flower();
        flower.setFlowerName("Jasmine");
        flower.setPhotoPath(R.drawable.jasmine);
        flowerData.add(flower);


        //4th Item
        flower = new Flower();
        flower.setFlowerName("Lily");
        flower.setPhotoPath(R.drawable.lily);
        flowerData.add(flower);


        //5th Item
        flower = new Flower();
        flower.setFlowerName("Poppy");
        flower.setPhotoPath(R.drawable.poppy);
        flowerData.add(flower);


        //6th Item
        flower = new Flower();
        flower.setFlowerName("Rose");
        flower.setPhotoPath(R.drawable.rose);
        flowerData.add(flower);

        return flowerData;

    }
}

Values Files

res/values/dimens.xml
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="gridView_cellWidth">160dp</dimen>
    <dimen name="gridView_cellHeight">160dp</dimen>
    <dimen name="cellText_padding">5dp</dimen>
    <dimen name="elementMargin">10dp</dimen>
    <dimen name="cellText_textSize">18sp</dimen>
</resources>
res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="overlay">#80000000</color>
    <color name="textColor">#ffffff</color>
</resources>
res/values/strings.xml
<resources>
    <string name="app_name">GridView Example</string>
</resources>

Output

screenshot_gridview

Complete Source Code

Complete source code of this project has been published in GitHub. It is free to use and customize. Please click on the below download button to see the GitHub repository.
 
Please ask your questions regarding this topic using the below comment section.
Thank you and good luck!
  • Was this tutorial helpful for you ?
  •  
  • yes   no

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap th...