Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.Note – We have used other widgets – imageView and textView in this tutorial. So, you may visit our tutorials on textView and imageView in kotlin.
If you wish to know more, you may visit official link of – this widget.
TABLE OF CONTENT
Output

GridView Output
SourceCode (Kotlin)
[emaillocker id=”4963″]
GridView Tutorial Source Code
[/emaillocker]
Getting Started
Android GridView can be defined 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.
Example of Android GridView Using Kotlin
Now, we will use android gridView widget in android application. We will see how to use ArrayAdapter or BaseAdapter with gridView using kotlin. At first, we will create an android application.
1. Creating New Project in Kotlin
Follow steps below to create new project. Please ignore the steps if you have already created the project.
Step | Description |
---|---|
1. | Open Android Studio. |
2. | Go to File => New => New Project. Write application name as GridView. Then, check Include Kotlin Support and click next button. |
3. | Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button |
4. | Then, select Empty Activity => click next => click finish. |
5. | You will get a newly created project successfully if you have followed steps properly. |
2. Modify values folder
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.
3. 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.
4. 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 internal class ImageListAdapter internal constructor(context: Context, private val resource: Int, private val itemList: Array<String>?) : ArrayAdapter<ImageListAdapter.ItemHolder>(context, resource) { override fun getCount(): Int { return if (this.itemList != null) this.itemList.size else 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val holder: ItemHolder if (convertView == null) { convertView = LayoutInflater.from(context).inflate(resource, null) holder = ItemHolder() holder.name = convertView!!.findViewById(R.id.textView) holder.icon = convertView.findViewById(R.id.icon) convertView.tag = holder } else { holder = convertView.tag as ItemHolder } holder.name!!.text = this.itemList!![position] holder.icon!!.setImageResource(R.mipmap.ic_launcher) return convertView } internal class ItemHolder { 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.
5. Use GridView Widget in xml file
Open src/main/res/layout/activity_main.xml file and add below code into it.
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" 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" />
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.
6. Access GridView using Kotlin file
Open src/main/java/com.tutorialwing.gridview/MainActivity.kt file and add below code into it.
package com.tutorialwing.gridview import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.GridView import android.widget.Toast class MainActivity : AppCompatActivity() { 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) setContentView(R.layout.activity_main) val gridview = findViewById<GridView>(R.id.gridview) val adapter = ImageListAdapter(this, R.layout.list_item, itemList) gridview.adapter = adapter } }
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.
7. Setting Item Click Listener in gridView
You can set item click listener in gridView using kotlin as below –
gridview.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id -> // Write code to perform action when item is clicked. }
Final MainActivity.kt Code
Final MainActivity.kt code will be as shown below –
package com.tutorialwing.gridview import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.GridView import android.widget.Toast class MainActivity : AppCompatActivity() { 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) setContentView(R.layout.activity_main) val gridview = findViewById<GridView>(R.id.gridview) val adapter = ImageListAdapter(this, R.layout.list_item, itemList) gridview.adapter = adapter gridview.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id -> Toast.makeText(this@MainActivity, " Clicked Position: " + (position + 1), Toast.LENGTH_SHORT).show() } } }
8. Custom Adapter Using BaseAdapter
You can also create adapter for gridView by inheriting it from BaseAdapter. You 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, You 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. |
You 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.
Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.
AndroidManifest.xml file
Code inside main/AndroidManifest.xml file is as below.
<?xml version="1.0" encoding="utf-8"?> <manifest package="com.tutorialwing.gridview" xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" 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>
When we run the program, we will get output as shown above.
That’s end of our tutorial on Android GridView using Kotlin.