Android GridView Using Kotlin With Example

In this article, we will learn about android GridView using Kotlin. We will go through various example that demonstrates how to use different attributes of GridView. For example,

In this article, we will get answer to questions like –

  • What is GridView?
  • Why should we consider GridView while designing ui for any app?
  • What are possibilities using GridView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

tutorialwing android GridView using kotlin tutorial with example output

GridView Output

Getting Started

We can define android GridView widget as below –

GridView is, a subclass of ViewGroup, a widget that are used to display items in 2-dimensional scrollable grid like view. You can use either BaseAdapter or ArrayAdapter or any other custom adapter to provide data in GridView.

Now, how do we use GridView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as GridView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android GridView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using GridView in Kotlin

Follow steps below to use GridView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">GridView</string>
    </resources>
    
  • Now, open res/values/dimens.xml file. Then, add below code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="img_width">50dp</dimen>
        <dimen name="img_height">50dp</dimen>
        <dimen name="txv_padding">16dp</dimen>
        <dimen name="padding_default">10dp</dimen>
    </resources>
    

    Note – If there is no dimens.xml file in res/layout folder, then, you need to create this file.

  • Create View For Single Item in GridView

    Now, you need to create a view for an item shown in gridView. So, create an xml file, named list_item.xml, in res/layout folder.

    Now, open main/res/layout/list_item.xml file. Then, add below code into this file.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:background="@android:color/white"
    	android:orientation="horizontal">
    
    	<ImageView
    		android:id="@+id/icon"
    		android:layout_width="@dimen/img_width"
    		android:layout_height="@dimen/img_height"/>
    
    	<TextView
    		android:id="@+id/textView"
    		android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:layout_gravity="center"
    		android:padding="@dimen/txv_padding"
    		android:textColor="@android:color/black"/>
    
    </LinearLayout>
    

    We are showing image and name of an item in gridView. So, there is imageView and textView in list_item.xml file.

  • Create Adapter For GridView

    Now, we will create an customer adapter for GridView that will be used to provide data to it.

    So, create a kotlin class, named ImageListAdapter.kt, file in main/java/com.tutorialwing.gridview folder. Then, add below code into it.

    package com.tutorialwing.gridview
    
    import android.content.Context
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.ArrayAdapter
    import android.widget.ImageView
    import android.widget.TextView
    import com.tutorialwing.gridview.databinding.ListItemBinding
    
    internal class ImageListAdapter internal constructor(
    	context: Context,
    	private val resource: Int,
    	private val itemList: Array<String>?
    ) : ArrayAdapter<ImageListAdapter.ItemViewHolder>(context, resource) {
    
    	private val inflater: LayoutInflater = LayoutInflater.from(context)
    	private lateinit var itemBinding: ListItemBinding
    
    	override fun getCount(): Int {
    		return if (this.itemList != null) this.itemList.size else 0
    	}
    
    	override fun getView(position: Int, view: View?, parent: ViewGroup): View {
    		var convertView = view
    		val holder: ItemViewHolder
    		if (convertView == null) {
    			itemBinding = ListItemBinding.inflate(inflater)
    			convertView = itemBinding.root
    			holder = ItemViewHolder()
    			holder.name = itemBinding.textView
    			holder.icon = itemBinding.icon
    			convertView.tag = holder
    		} else {
    			holder = convertView.tag as ItemViewHolder
    		}
    		holder.name!!.text = this.itemList!![position]
    		holder.icon!!.setImageResource(R.mipmap.ic_launcher)
    		return convertView
    	}
    
    	internal class ItemViewHolder {
    		var name: TextView? = null
    		var icon: ImageView? = null
    	}
    }
    

    As we already know, this class provides data for an item to the GridView. We have inherited this class from ArrayAdapter class. A constructor has also been defined that accepts context, resourceId and itemList. resourceId is id of xml layout file of single item. Then, we have overridden some of the methods in this class.

    They are –

    S. No. Method Description
    1. getCount() It returns the number of elements in item list provided to adapter class. Number of grids in gridView will be equal to number of elements
    2. getView() Returns the view at given position in the adapter. Here, It’s using class ItemHolder to recycle/reuse the already created View. Note that a view is created only when convertView is null. Otherwise, it’s returning already created view.

    Since adapter class is ready, we will use GridView widget in xml file. Then, we will access this GridView using kotlin file and perform some operations on it.

  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <GridView
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:horizontalSpacing="@dimen/padding_default"
            android:numColumns="auto_fit"
            android:padding="@dimen/padding_default"
            android:verticalSpacing="@dimen/padding_default"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    In activity_main.xml file, we have used gridView widget. This widget is responsible for providing view like grid. Now, we will access this gridView using kotlin file and perform some actions on it.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.gridview
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.AdapterView
    import android.widget.Toast
    import com.tutorialwing.gridview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	private val itemList: Array<String>
    		get() = arrayOf(
    			"Item 1",
    			"Item 2",
    			"Item 3",
    			"Item 4",
    			"Item 5",
    			"Item 6",
    			"Item 7",
    			"Item 8",
    			"Item 9",
    			"Item 10",
    			"Item 11",
    			"Item 12",
    			"Item 13",
    			"Item 14",
    			"Item 15",
    			"Item 16",
    			"Item 17",
    			"Item 18",
    			"Item 19",
    			"Item 20",
    			"Item 21",
    			"Item 22"
    		)
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupGridView()
    	}
    
    	private fun setupGridView() {
    		val adapter = ImageListAdapter(this, R.layout.list_item, itemList)
    		binding.gridview.adapter = adapter
    
    		binding.gridview.onItemClickListener =
    			AdapterView.OnItemClickListener { parent, v, position, id ->
    				Toast.makeText(
    					this@MainActivity, " Clicked Position: " + (position + 1),
    					Toast.LENGTH_SHORT
    				).show()
    			}
    	}
    }
    

    Here, we have accessed gridView using kotlin file i.e. In MainActivity.kt file. Then, an instance of ImageListAdapter class has been created. Then, this adapter class is set as an adapter of gridView.

    After that we have set click listener (ItemClickListener) to gridView.

Now, run the application. We will get output as below –

tutorialwing android GridView using kotlin tutorial with example output

GridView Output

Custom Adapter Using BaseAdapter

We can also create adapter for gridView by inheriting it from BaseAdapter. We can do it as below –

Create a new file, named ImageAdapter.kt, in main/java/com.tutorialwing.gridview folder. Then, add below code into it.

package com.tutorialwing.gridview

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter internal constructor(private val mContext: Context) : BaseAdapter() {

	// References to our images
	private val mThumbIds = arrayOf(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)

	override fun getCount(): Int {
		return mThumbIds.size
	}

	override fun getItem(position: Int): Any? {
		return null
	}

	override fun getItemId(position: Int): Long {
		return 0
	}

	// Create a new ImageView for each item referenced by the Adapter
	override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
		val imageView: ImageView
		if (convertView == null) {
			// if it's not recycled, initialize some attributes
			imageView = ImageView(mContext)
			imageView.layoutParams = ViewGroup.LayoutParams(300, 300)
			imageView.scaleType = ImageView.ScaleType.CENTER_CROP
		} else {
			imageView = (convertView as ImageView?)!!
		}

		imageView.setImageResource(mThumbIds[position])
		return imageView
	}
}

In this file, a single element contains only image. So, We can download all the drawable images here. Then, unzip the file and put all the images in res/drawable folder.

In this file, following methods have been overridden in this file –

S. No. Method Description
1. getCount() It returns the number of elements in item list provided to adapter class. Number of grids in gridView will be equal to number of elements
2. getView() Returns the view at given position in the adapter. Here, It’s using class ItemHolder to recycle/reuse the already created View. Note that a view is created only when convertView is null. Otherwise, it’s returning already created view.
3. getItem() Returns the item present at given position.
4. getItemId() Returns the id of the item at given position.

We can set this adapter in gridView as below –

gridview.adapter = ImageAdapter(this)

Difference between BaseAdapter and ArrayAdapter

BaseAdapter is abstract while ArrayAdapter extends BaseAdapter. If you are using ArrayAdapter, you inherits all the features implemented in ArrayAdapter. But, if you are using BaseAdapter, you will have to implements all the abstract methods.

Different Attributes of GridView in XML

Now, we will see how to use different attributes of Android GridView using Kotlin to customise it –

Set Id of GridView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of GridView using android:id attribute like below –

    <GridView
        android:id="@+id/gridView_ID"
        />

Here, we have set id of GridView as gridView_ID using android:id=”” attribute. So, if we need to reference this GridView, we need to use this id – gridView_ID.
Learn to Set ID of GridView Dynamically

Set Width of GridView

We use android:layout_width=”” attribute to set width of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of GridView Dynamically

Set Height of GridView

We use android:layout_height=”” attribute to set height of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of GridView Dynamically

Set Padding of GridView

We use android:padding=”” attribute to set padding of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in GridView using android:padding=”” attribute.
Learn to Set Padding of GridView Dynamically

Set Margin of GridView

We use android:layout_margin=”” attribute to set margin of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in GridView using android:layout_margin=”” attribute.
Learn to Set Margin of GridView Dynamically

Set Background of GridView

We use android:background=”” attribute to set background of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in GridView using android:background=”” attribute.
Learn to Set Background of GridView Dynamically

Set Visibility of GridView

We use android:visibility=”” attribute to set visibility of GridView.
We can do it as below –

    <GridView
        android:id="@+id/gridView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of GridView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of GridView Dynamically

Thus, we have seen what is GridView, how can we use android GridView using Kotlin ? etc. We also went through different attributes of android GridView.

Leave a Reply