Android GridLayoutManager: 7 RecyclerView Setup Tips

Android GridLayoutManager: 7 RecyclerView Setup Tips - Image

RecyclerView is a powerful tool to draw lists or grids in your android application, When RecyclerView is not there then the user needs GridView for the grid.

But now android provides a great tool RecyclerView to draw both with one single view list and grid. Android RecyclerView is a more advanced, powerful, and flexible version of the GridView. Android RecyclerView is similar to ListView but with the help of GridLayoutManager, you can draw a grid.

As with material design, a new view was introduced through the support v7 library, called CardView. We will show you how Android CardView can be implemented in a RecyclerView list. Android CardView provides a more advanced and flexible way of implementing complex and custom listview and gridview with more functionality that is required for your apps.

The RecyclerView is available in the support library. So we need to add one script in Gradle dependency:

compile 'com.android.support:recyclerview-v7:23.0.1'

To use the CardView in your app, add the CardView dependency in gradle:

compile 'com.android.support:cardview-v7:23.0.1'

If you want to include card view with your RecyclerView list then you have to need both in your Gradle file like this:

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:recyclerview-v7:23.0.1'
    compile 'com.android.support:cardview-v7:23.0.1'
}

For creating a grid you require to add GridLayoutManager and you can set custom column detail like 2, 3, etc. :

    private GridLayoutManager gridLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        gridLayoutManager = new GridLayoutManager(this, <number of your column>); // 
        .
        .
        .
        .
        .

RecyclerView

RecyclerView code example for your layout:

Check the Project’s Android Dependencies

Legacy support libraries and AndroidX

This example uses older android.support package names and a compile-style dependency declaration. Treat those snippets as legacy reference material, not a drop-in configuration for a modern project. Current Android projects commonly use AndroidX packages and dependency versions managed by the project’s Gradle configuration. Follow the dependency style already used by the app and avoid mixing old support-library artifacts with AndroidX classes.

Before copying code, check the module’s existing Gradle files, plugin configuration, and imports. If migrating an older app, make the dependency change consistently and build the project before changing the adapter or layout. A missing class or duplicate dependency is often a sign that the project’s libraries are mixed, not that GridLayoutManager itself is configured incorrectly.

Confirm the project setup first

Check the Android Gradle Plugin and SDK settings used by the project, then select compatible RecyclerView and CardView libraries if CardView is needed. Use the project’s dependency catalog or version management convention when one exists. Avoid copying a version number from an old tutorial without checking whether it fits the app’s current build.

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.legendblogs.demorecyclercardview.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        />
</RelativeLayout>

CardView

CardView code example for your layout with your required tools :

Prepare the Grid Item and Data

Keep each item layout focused

A grid cell should have a clear content hierarchy and a predictable width. In a two-column grid, a card that assumes the full screen width can force awkward wrapping or oversized gaps. Use flexible widths, sensible padding, and text that can wrap or truncate in an accessible way. Preview the item with both short and long sample values.

Keep model data independent of views

The data model should describe the item rather than hold references to activity views. Keep values such as a title, description, image identifier, or stable ID in the model, then let the adapter bind those values into the view holder. This separation makes it easier to test data changes and avoids coupling the dataset to one screen instance.

<?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"
    android:tag="cards main container">
    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="10dp"
        card_view:cardUseCompatPadding="true">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_weight="2"
            android:orientation="vertical"
            >
            <TextView
                android:id="@+id/text_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="dfsdf sdf sdf"
                android:layout_marginLeft="15dp"
                android:textStyle="bold" />
            <TextView
                android:id="@+id/text_desc"
                android:layout_width="wrap_content"
                android:text="sdfsdff"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="15dp"
                android:layout_marginBottom="10dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

The MainActivity.java class is defined below like this:

package com.legendblogs.demorecyclercardview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    private static RecyclerView.Adapter adapter;
    private static RecyclerView recyclerView;
    private static ArrayList<DataModel> data;
    private GridLayoutManager gridLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);
        gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        data = new ArrayList<DataModel>();
        for (int i = 0; i < DataSet.title_Array.length; i++) {
            data.add(new DataModel(
                    DataSet.title_Array[i],
                    DataSet.desc_Array[i]
            ));
        }
        adapter = new CustomAdapter(data);
        recyclerView.setAdapter(adapter);
    }
}

Configure GridLayoutManager and the Adapter

Choose a column count that fits the content

GridLayoutManager takes a span count that determines how many columns are shown for the available layout. A fixed count is straightforward when the design requires a known number of columns, but the same value may feel cramped on a narrow phone or sparse on a wide tablet. Consider the minimum usable cell width and test the layout at different screen sizes and orientations.

Choose fixed or content-aware spans

A fixed span count is predictable and easy to reason about, which makes it useful for a simple card grid. If the design must adapt across phones, tablets, and resizable windows, calculate the number of columns from the available width and a minimum acceptable cell size. Recalculate when the container size changes, and keep the chosen count within sensible limits so a very wide window does not create unreadably narrow cards.

Test a range of item counts, including a final row that is not full. Check whether card widths, text wrapping, and spacing remain balanced when the orientation changes. The layout should remain understandable when there are only a few items as well as when the dataset fills many rows.

Attach the layout manager before checking the result

Set the layout manager on the RecyclerView, create the adapter with the data collection, and assign the adapter to the view. If the grid is blank, verify that the RecyclerView has a measured height and width, the layout manager is attached, the adapter returns a nonzero item count, and the item view uses the correct resource ID. Also inspect runtime logs for inflation or binding errors.

Steps for building and testing an Android RecyclerView grid
Build an Android RecyclerView Grid

DataSet for the list 

package com.legendblogs.demorecyclercardview;
public class DataSet {
    static String[] title_Array = {"JellyBean", "Kitkat", "Lollipop", "Marshmallow", "Nougat", "Oreo"};
    static String[] desc_Array = {"4.1", "4.4", "5.0","6.0","7.0", "8.0"};
}

DataModel for the list:

package com.legendblogs.demorecyclercardview;
public class DataModel {
    String title;
    String desc;
    public DataModel(String title, String desc) {
        this.title = title;
        this.desc = desc;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
}

Update Grid Items Without Stale Displays

Change the data source deliberately

When new items arrive, update the collection that the adapter actually reads, then notify the adapter using an update strategy appropriate for the change. Replacing the entire dataset, inserting one item, and changing a single field are different operations; using an overly broad refresh can cause unnecessary rebinding, while notifying the wrong position can leave the display inconsistent.

For a larger or frequently changing list, use a diff-based list approach so the UI can identify inserted, removed, and changed items. Keep item identity stable where possible, and do not mutate a list silently while the RecyclerView is drawing it. When data comes from a background task, deliver UI updates on the main thread through the app’s normal lifecycle-aware pattern.

CustomAdapter for the list:

package com.legendblogs.demorecyclercardview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
    private ArrayList<DataModel> dataModel;
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView text_title;
        TextView text_desc;
        public MyViewHolder(View view) {
            super(view);
            this.text_title = (TextView) view.findViewById(R.id.text_title);
            this.text_desc = (TextView) view.findViewById(R.id.text_desc);
        }
    }
    public CustomAdapter(ArrayList<DataModel> data) {
        this.dataModel = data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cards_layout, parent, false);
       // view.setOnClickListener(MainActivity.myOnClickListener);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }
    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        TextView text_title = holder.text_title;
        TextView text_desc = holder.text_desc;
        text_title.setText(dataModel.get(position).getTitle());
        text_desc.setText(dataModel.get(position).getDesc());
    }
    @Override
    public int getItemCount() {
        return dataModel.size();
    }
}

Spacing, Clicks, and Accessibility

Control spacing at the RecyclerView level

Grid gaps can be managed with an item decoration that accounts for the column index and outer edges. This is generally easier to maintain than adding unrelated margins to every card, which can make the outside padding uneven. Test both the first and last row, because spacing formulas that work between cells can create an oversized border around the grid.

Make each interactive cell understandable

If a cell opens another screen or performs an action, give it a clear accessible label and a touch target that is comfortable to use. Do not communicate item state through color alone. Check how keyboard or assistive-technology focus moves through the grid, and ensure that text descriptions are available when images carry important information.

Troubleshoot Common Grid Problems

Investigate uneven or blank cells

Start by checking the item layout’s width and height, the adapter’s item count, and whether each bound view receives the expected data. Long text may expand one item if dimensions are not constrained, while a missing image or invalid resource can interrupt binding. Test with a small, known dataset and add fields back one at a time.

Check nesting and scrolling behavior

A RecyclerView placed inside another scrolling container can create measurement and performance problems, especially when both views compete to handle vertical gestures. Prefer a single scrolling surface when possible. If nested scrolling is necessary, validate the measured height, gesture behavior, and accessibility navigation on real devices rather than relying only on a preview.

Android phone displaying an app interface
Check grid behavior on device sizes that your app supports. · Photo: freestocks.org / Openverse (CC0)

Related posts

(1) Comments

  • User Pic

    Great Stuff ..

Write a comment