A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array. The adapter is used for displaying this data, setAdapter() method is used to join the adapter with GridView. The main function of the adapter in GridView is to fetch data from a database or array and insert each piece of data in an appropriate item that will be displayed in GridView. This is what the GridView structure looks like. We are going to implement this project using both Java and Kotlin Programming Language for Android.
XML Attributes of GridView
- android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid.
- android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView.
- android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView.
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. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Add the Required Dependencies
Add the Google Repository to your settings.gradle File.
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { // add the following google() mavenCentral() } }
After adding this Dependency, Sync the Project and now we will move towards its implementation.
Step 3: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. 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" ?> < androidx.constraintlayout.widget.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > <!-- android:numColumns=2 is the number of columns for Grid View android:horizontalSpacing is the space between horizontal grid items --> < GridView android:id = "@+id/idGVcourses" android:layout_width = "match_parent" android:layout_height = "match_parent" android:horizontalSpacing = "6dp" android:numColumns = "2" android:verticalSpacing = "6dp" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
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 card_item. Below is the code for the card_item.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!-- XML implementation of Card Layout --> < androidx.cardview.widget.CardView android:layout_width = "match_parent" android:layout_height = "120dp" 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 = "100dp" android:layout_height = "100dp" android:layout_gravity = "center" android:src = "@mipmap/ic_launcher" /> < TextView android:id = "@+id/idTVCourse" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "@string/app_name" android:textAlignment = "center" /> </ LinearLayout > </ androidx.cardview.widget.CardView > |
Step 5: Create a Model Class for Storing Data
Model Class is the Java/Kotlin Class that handles data to be added to each GridView item of GridView. For Creating Model Class.
Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java/Kotlin Class file as CourseModel. Below is the code for the <CourseModel file.
Java
public class CourseModel { // string course_name for storing course_name // and imgid for storing image id. private String course_name; private int imgid; public CourseModel(String course_name, int imgid) { this .course_name = course_name; this .imgid = imgid; } public String getCourse_name() { return course_name; } public void setCourse_name(String course_name) { this .course_name = course_name; } public int getImgid() { return imgid; } public void setImgid( int imgid) { this .imgid = imgid; } } |
Kotlin
class CourseModel(var course_name: String, var imgid: Int) { fun getCourse_name(): String { return course_name } fun setCourse_name(course_name: String) { this .course_name = course_name } fun getImgid(): Int { return imgid } fun setImgid(imgid: Int) { this .imgid = imgid } } |
Step 6: Create an 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.
Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter file.
Java
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 androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter<CourseModel> { public CourseGVAdapter( @NonNull Context context, ArrayList<CourseModel> courseModelArrayList) { super (context, 0 , courseModelArrayList); } @NonNull @Override public View getView( int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null ) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false ); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; } } |
Kotlin
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 class CourseGVAdapter(context: Context, courseModelArrayList: ArrayList<CourseModel?>?) : ArrayAdapter<CourseModel?>(context, 0 , courseModelArrayList) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var listitemView = convertView if (listitemView == null ) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false ) } val courseModel: CourseModel? = getItem(position) val courseTV = listitemView!!.findViewById<TextView>(R.id.idTVCourse) val courseIV = listitemView.findViewById<ImageView>(R.id.idIVcourse) courseTV.setText(courseModel.getCourse_name()) courseIV.setImageResource(courseModel.getImgid()) return listitemView } } |
Step 7: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle; import android.widget.GridView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>(); courseModelArrayList.add( new CourseModel( "DSA" , R.drawable.ic_gfglogo)); courseModelArrayList.add( new CourseModel( "JAVA" , R.drawable.ic_gfglogo)); courseModelArrayList.add( new CourseModel( "C++" , R.drawable.ic_gfglogo)); courseModelArrayList.add( new CourseModel( "Python" , R.drawable.ic_gfglogo)); courseModelArrayList.add( new CourseModel( "Javascript" , R.drawable.ic_gfglogo)); courseModelArrayList.add( new CourseModel( "DSA" , R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter( this , courseModelArrayList); coursesGV.setAdapter(adapter); } } |
Kotlin
import android.os.Bundle import android.widget.GridView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var coursesGV: GridView override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) coursesGV = findViewById(R.id.idGVcourses) val courseModelArrayList: ArrayList<CourseModel> = ArrayList<CourseModel>() courseModelArrayList.add(CourseModel( "DSA" , R.drawable.ic_gfglogo)) courseModelArrayList.add(CourseModel( "JAVA" , R.drawable.ic_gfglogo)) courseModelArrayList.add(CourseModel( "C++" , R.drawable.ic_gfglogo)) courseModelArrayList.add(CourseModel( "Python" , R.drawable.ic_gfglogo)) courseModelArrayList.add(CourseModel( "Javascript" , R.drawable.ic_gfglogo)) courseModelArrayList.add(CourseModel( "DSA" , R.drawable.ic_gfglogo)) val adapter = CourseGVAdapter( this , courseModelArrayList) coursesGV.adapter = adapter } } |