⇒ 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.
<?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" tools:context=".MainActivity"> <!--on below line we are creating a grid view--> <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>
- we need to set each item of our list into grids with helps some item file to set each elements values
Item_resource.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dp" app:cardCornerRadius="5dp" app:cardElevation="5dp"> <!--on below line we are creating a linear layout for grid view item--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--on below line we are creating a simple image view--> <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" /> <!--on below line we are creating a simple text view--> <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>