Android GridView in Kotlin
Last Updated :
06 Jun, 2022
A Grid View is a type of adapter view that is used to display the data in the grid layout format. For setting the data to the grid view adapter is used with the help of the setAdapter() method. This adapter helps to set the data from the database or array list to the items of the grid view. In this article, we will take a look at How to implement Grid View in Android using Kotlin language. A sample video is given below to get an idea about what we are going to do in this article.
Note: If you are looking to implement Grid View in Android using Java. Check out the following article: Grid View in Android using Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< GridView
android:id = "@+id/idGRV"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:horizontalSpacing = "6dp"
android:numColumns = "2"
android:verticalSpacing = "6dp" />
</ RelativeLayout >
|
Step 3: Create an XML layout file for each item of GridView
Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as gridview_item. Below is the code for the gridview_item.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.cardview.widget.CardView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_margin = "5dp"
app:cardCornerRadius = "5dp"
app:cardElevation = "5dp" >
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical" >
< ImageView
android:id = "@+id/idIVCourse"
android:layout_width = "80dp"
android:layout_height = "80dp"
android:layout_gravity = "center"
android:layout_margin = "5dp"
android:padding = "4dp"
android:src = "@mipmap/ic_launcher" />
< TextView
android:id = "@+id/idTVCourse"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_margin = "5dp"
android:padding = "4dp"
android:text = "@string/app_name"
android:textAlignment = "center"
android:textColor = "@color/black" />
</ LinearLayout >
</ androidx.cardview.widget.CardView >
|
Step 4: Create a Modal Class for storing Data
Modal Class is the JAVA Class that handles data to be added to each GridView item of GridView. For Creating Modal Class. Navigate to app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as GridViewModal and add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
data class GridViewModal(
val courseName: String,
val courseImg: Int
)
|
Step 5: Creating the Adapter class
Adapter Class adds the data from Modal Class in each item of GridView which is to be displayed on the screen. For Creating Adapter Class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as GridRVAdapter and add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
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
internal class GridRVAdapter(
private val courseList: List<GridViewModal>,
private val context: Context
) :
BaseAdapter() {
private var layoutInflater: LayoutInflater? = null
private lateinit var courseTV: TextView
private lateinit var courseIV: ImageView
override fun getCount(): Int {
return courseList.size
}
override fun getItem(position: Int): Any? {
return null
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
var convertView = convertView
if (layoutInflater == null ) {
layoutInflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
if (convertView == null ) {
convertView = layoutInflater!!.inflate(R.layout.gridview_item, null )
}
courseIV = convertView!!.findViewById(R.id.idIVCourse)
courseTV = convertView!!.findViewById(R.id.idTVCourse)
courseIV.setImageResource(courseList.get(position).courseImg)
courseTV.setText(courseList.get(position).courseName)
return convertView
}
}
|
Step 6: Adding images to the drawable folder
Copy your images. And navigate to the app > res > drawable > Right-click on it and paste all the images which are copies within the drawable folder. Refer to this article How to Add Image to Drawable Folder in Android Studio
Step 7: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.os.Bundle
import android.widget.AdapterView
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
lateinit var courseGRV: GridView
lateinit var courseList: List<GridViewModal>
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
courseGRV = findViewById(R.id.idGRV)
courseList = ArrayList<GridViewModal>()
courseList = courseList + GridViewModal( "C++" , R.drawable.c)
courseList = courseList + GridViewModal( "Java" , R.drawable.java)
courseList = courseList + GridViewModal( "Android" , R.drawable.android)
courseList = courseList + GridViewModal( "Python" , R.drawable.python)
courseList = courseList + GridViewModal( "Javascript" , R.drawable.js)
val courseAdapter = GridRVAdapter(courseList = courseList, this @MainActivity )
courseGRV.adapter = courseAdapter
courseGRV.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
Toast.makeText(
applicationContext, courseList[position].courseName + " selected" ,
Toast.LENGTH_SHORT
).show()
}
}
}
|
Now run your application to see the output of it.
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...