Android GridLayoutManager Example
In Android development, RecyclerView is a powerful view for displaying a large dataset in a scrollable list. One of the key components that determine how the data is laid out within the RecyclerView is the LayoutManager. The GridLayoutManager is a type of LayoutManager that arranges items in a grid-like structure. This blog post will provide a detailed example of how to use the GridLayoutManager in an Android application.
Table of Contents#
- Prerequisites
- Setting up the Project
- Creating the Layout Files
- Creating the Adapter
- Implementing the GridLayoutManager
- Common Practices and Best Practices
- Conclusion
- References
1. Prerequisites#
- Basic knowledge of Android development using Java or Kotlin.
- Android Studio installed on your machine.
- Familiarity with RecyclerView and its basic concepts.
2. Setting up the Project#
- Open Android Studio and create a new Android project.
- Select the
Empty Activitytemplate and clickNext. - Configure your project details such as the app name, package name, and save location. Then click
Finish.
3. Creating the Layout Files#
activity_main.xml#
This is the main layout file for the activity. It will contain a RecyclerView to display the grid of items.
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>item_layout.xml#
This layout file defines the appearance of each item in the grid.
<?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="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />
</LinearLayout>4. Creating the Adapter#
The adapter is responsible for providing data to the RecyclerView and creating views for each item.
Java#
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<String> dataList;
public MyAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String item = dataList.get(position);
holder.textView.setText(item);
}
@Override
public int getItemCount() {
return dataList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.item_text);
}
}
}Kotlin#
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter(private val context: Context, private val dataList: List<String>) :
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = dataList[position]
holder.textView.text = item
}
override fun getItemCount(): Int {
return dataList.size()
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.item_text)
}
}5. Implementing the GridLayoutManager#
In the MainActivity, we will set up the RecyclerView and use the GridLayoutManager to arrange the items in a grid.
Java#
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
private List<String> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
// Initialize data
dataList = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
dataList.add("Item " + i);
}
// Create the adapter
adapter = new MyAdapter(this, dataList);
// Set the GridLayoutManager
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}Kotlin#
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: MyAdapter
private val dataList = ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
// Initialize data
for (i in 1..20) {
dataList.add("Item $i")
}
// Create the adapter
adapter = MyAdapter(this, dataList)
// Set the GridLayoutManager
val layoutManager = GridLayoutManager(this, 2)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
}
}6. Common Practices and Best Practices#
- Item Decoration: You can add an
ItemDecorationto the RecyclerView to add spacing between items in the grid. For example:
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private final int spacing;
public GridSpacingItemDecoration(int spacing) {
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = spacing;
outRect.right = spacing;
outRect.top = spacing;
outRect.bottom = spacing;
}
}And then add it to the RecyclerView:
recyclerView.addItemDecoration(new GridSpacingItemDecoration(16));- Span Size Lookup: If you want to have items that span multiple columns in the grid, you can use the
setSpanSizeLookupmethod of theGridLayoutManager. For example, if you want the first item to span two columns:
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return position == 0 ? 2 : 1;
}
});7. Conclusion#
The GridLayoutManager is a powerful tool for arranging items in a grid-like structure within a RecyclerView. By following the steps in this example, you can easily implement a grid layout in your Android application. Remember to use best practices such as adding item decorations and customizing the span size lookup to enhance the user experience.