How to Implement GridView Inside a Fragment in Android?
Last Updated :
24 Apr, 2025
A GridView is a versatile and efficient widget that allows you to display items in a grid-like fashion, perfect for presenting images, icons, or any structured data. Fragments, on the other hand, are essential components for building flexible and modular user interfaces. They enable the creation of reusable UI components that can be combined to create rich and responsive layouts.
In this article, we will go through the process of implementing a GridView inside a Fragment in your Android application. This article will provide you with the knowledge and steps needed to create engaging grid-based interfaces within your app.
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: Change the StatusBar Color
Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.
<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>
Step 3: Creating a new Fragment
In this step, we have to create a new Fragment named as fragment.
-min-min-(1)-(1).png)
Click on Fragment(Blank) and create a new Fragment.
Step 4: Working with fragment_first.xml
Navigate to app > res > layout > fragment.xml. In this fragment layout file, we are going to implement the GridView.
XML
<?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:orientation="vertical">
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:padding="10dp"/>
</LinearLayout>
Step 5: Working with activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. In this layout, we have created a button by clicking this button the fragment layout with GridView will be displayed.
XML
<?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">
<!--Frame layout-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame_layout">
<!--Button-->
<Button
android:id="@+id/btn_frag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:foreground="?attr/selectableItemBackground"
android:text="Open GridView in Fragment"/>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Working with fragment.kt
Navigate to the app > java >your package name > fragment, in this file, we are going to initialize the GridView and its adapter within the onCreateView method. Add the below code to your fragment.kt file.
Kotlin
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val rootView = inflater.inflate(R.layout.fragment, container, false)
val gridView = rootView.findViewById<GridView>(R.id.grid_view)
// Set up the adapter and item click listener for the grid view
val adapter = ArrayAdapter<String>(requireContext(), android.R.layout.simple_list_item_1, getData())
gridView.adapter = adapter
// Handle item click in the grid view
gridView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
// Handle item click here
val selectedItem = adapter.getItem(position)
// Perform actions based on the selected item
}
return rootView
}
Full Code of the fragment.kt:
Kotlin
package com.example.gfg
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.GridView
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [fragment.newInstance] factory method to
* create an instance of this fragment.
*/
class fragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val rootView = inflater.inflate(R.layout.fragment, container, false)
val gridView = rootView.findViewById<GridView>(R.id.grid_view)
// Set up the adapter and item click listener for the grid view
val adapter = ArrayAdapter<String>(requireContext(), android.R.layout.simple_list_item_1, getData())
gridView.adapter = adapter
// Handle item click in the grid view
gridView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
// Handle item click here
val selectedItem = adapter.getItem(position)
// Perform actions based on the selected item
}
return rootView
}
// Replace this with your data source
private fun getData(): List<String> {
return listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment fragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
fragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
Step 7: Working with MainActivity.kt
Navigate to the app > java >your package name > MainActivity, in this step we are going to setOnclickListener to the button and replace the FrameLayout with the Fragment with GridView.
Kotlin
package com.example.gfg
import android.opengl.Visibility
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set the activity's layout from the XML layout resource file
setContentView(R.layout.activity_main)
// Find the "btn_frag" button in the layout
val btn_frag: Button = findViewById(R.id.btn_frag)
// Set an OnClickListener for the "btn_frag" button
btn_frag.setOnClickListener {
// Create a new instance of the "fragment" class
val fragmentInstance = fragment()
// Begin a transaction to add the fragment to the "frame_layout" container
supportFragmentManager.beginTransaction()
.add(R.id.frame_layout, fragmentInstance)
.commit()
btn_frag.visibility= View.GONE
}
}
}
Output:
Similar Reads
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI fl
4 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. Â A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It h
12 min read
How to Implement onBackPressed() in Fragments in Android?
In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBac
3 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. fin
3 min read
How to Implement View Binding Inside Dialog in Android?
In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views th
4 min read
How to Implement Stepper Functionality in Android?
A Stepper widget allows you to organize content in a sequence of steps, and the user can navigate between them. In this article we are going to implement a Stepper-like functionality in an Android app here we take the help of Tablayout to achieve this. A Sample video is attached below to get an idea
4 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this
8 min read
How to Implement Item Click Interface in Android?
When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. What we are going to build in this article?In this article, we will be usin
5 min read
How to Implement Shapeable ImageView in Android?
In Android, ShapeableImageView is used to change the shape of your image to circle, diamond, etc. Also, you can set a corner radius to your ImageView. You can do much more by using this ShapeableImageView with minimal code. So in this article, we are going to make a ShapableImageView in android. By
5 min read
How to Implement Glassmorphism in Android?
Glassmorphism or BlurView is a style, developed by adopting the behavior of glass to enhance your app design. It gives a look and feel of translucent or transparent elements. Glassmorphic elements and shapes work really well on bright colorful backgrounds which accentuate the glass effect. So, we wi
2 min read