Open In App

How to Implement GridView Inside a Fragment in Android?

Last Updated : 24 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Screenshot-(387)-min-min-(1)-(1)

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 
    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: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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads