Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)
Asked Answered
R

8

308

I know that RecyclerView has replaced the functionality of the old ListView and GridView. I am looking for a very basic example that shows a minimal grid setup using RecyclerView. I am not looking for long tutorial style explanations, just a minimal example. I imagine the simplest grid that mimics the old GridView would consist of the following features:

  • multiple cells per row
  • single view in each cell
  • responds to click events
Rutaceous answered 14/11, 2016 at 11:2 Comment(0)
R
746

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

enter image description here

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

Auto-fitting columns

Further study

Rutaceous answered 14/11, 2016 at 11:2 Comment(20)
your grid is not equally disctibuted on the space it has - there is a padding on the rightHandball
@MarianPaździoch, Yes, I just made this as a minimal example. It could definitely use some beautification work. I'll try to update this answer some time in the future.Rutaceous
I wouldn't call this a beautification. This is a bug. A beautification would be to change those pink rectangles to kitten pictures.Handball
I logged in just to point that people like you have kept this portal alive and kicking .i was stuck on this for two days before seeing this solution. thanks a lotAbattoir
Tiny question: the default orientation of GridLayoutManager is Vertical, right?Berlinda
@androiddeveloper, The grid items get laid out left to right, top to bottom. Scrolling is vertical when there are more items than can fit on the screen.Rutaceous
@Rutaceous I see, so it is considered "vertical", right? It's just that it has other CTORs, with orientation.Berlinda
@androiddeveloper, I don't know. I've only used "vertical" and "horizontal" with the LinearLayoutManager for lists. If you find a way to do top to bottom, left to right (horizontal scroll) let me know.Rutaceous
@Rutaceous I'm sure it's about the same as there, just a bit more confusing because of multiple cells.Berlinda
@Rutaceous Thank you for your great answer. I have adapted upon in and managed to create a RecyclerView w/ images, but having issues with onclick. I have the creation of the recyclerView and the adapter in a runnable wrapped inside a void function. When I try to do the following: 'adapter.setClickListener(this)' I get an error saying it cannot be applied. If I create an itemClickListener as such: 'MyRecyclerViewAdapter.ItemClickListener itemClickListener' and then call adapter.setClickListener(itemClickListener) I get an error telling me that itemClickListener is not initialised.Microtome
I solved the problem by initialising the itemClickListener in main activity as such: ` itemClickListener = new MyRecyclerViewAdapter.ItemClickListener() { @Override public void onItemClick(View view, int position) { Log.i("TAG"); } };`Microtome
I don't think you need to save the context on the constructor to do this.mInflater = LayoutInflater.from(context);, you could just use: LayoutInflater.from(parent.getContext()) and not hold a reference to Context.Duyne
Answer is good but wondering why adapter.setClickListener(this); ?Hemipode
@AliAkram, because this refers to MainActivity, which implements MyRecyclerViewAdapter.ItemClickListener. So basically, this is just telling the adapter that any time a user clicks an item, send a notification to the activity. The activity will handle it in onItemClick(). Instead of this (the activity), it would also be possible to let another class handle the click event.Rutaceous
@mFeinstein, I'm saving a reference to the inflater, not to the context directly. However, I don't know if the inflater holds on to a reference to the context itself. If it does, then no matter whether you used the parameter variable context or got the context from parent.getContext(), the effect would be the same: The inflater is holding on to a reference to the context. I'm not aware of this being a problem, though. Have you found this to cause a memory leak?Rutaceous
@Rutaceous I didn't investigate this in depth, I just use parent.getContext() because it's simpler, but sometimes it will be desired to have the context injected for texting purposes (DI)Duyne
Future readers, let me save you some time, key thing is recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));Pontoon
@daka, good point. I edited my answer to include this in the beginning.Rutaceous
I set my item height to wrap_content and when i terminate the application and again open it from the recent the height of the item becomes 0 and it is not able to update the item height.Rascality
also in xml you can just add these app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" app:spanCount="2"Marvelous
D
16

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/personListRecyclerView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="2" />
Drumm answered 14/10, 2020 at 14:7 Comment(0)
P
12

Although I do like and appreciate Suragch's answer, I would like to leave a note because I found that coding the Adapter (MyRecyclerViewAdapter) to define and expose the Listener method onItemClick isn't the best way to do it, due to not using class encapsulation correctly. So my suggestion is to let the Adapter handle the Listening operations solely (that's his purpose!) and separate those from the Activity that uses the Adapter (MainActivity). So this is how I would set the Adapter class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

Please note the onItemClick method now defined in MyRecyclerViewAdapter that is the place where you would want to code your tasks for the event/action received.

There is only a small change to be done in order to complete this transformation: the Activity doesn't need to implement MyRecyclerViewAdapter.ItemClickListener anymore, because now that is done completely by the Adapter. This would then be the final modification:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}
Precarious answered 21/8, 2017 at 0:23 Comment(3)
What if the activity does need to listen to the click events? e.g. passing data to presenter, doing some logic based on item clicked, tracking, etc.Foreground
I agree that Adapter should handle click events, since it has the items with the data in it. @AhmadFadli if you need to do some work in the adapter's host (a Fragment or Activity) you should create a callback interface with methods you need. Your host implements this interface. And then you pass an instance of your host into Adapter's constructor. Having the instance of the host you can call it's methods when you need from your Adapter. And your host we get callbacks called. This is often used when you need to work with ActionMode. When you longClick to select items and use ActionBar buttons.Leund
I disagree and think that click events should be processed in the hosting Activity. Because only it's click listener can know about the Activity views and other Fragments, Activities, etc. The adapter can only send click events to upper level. It should have the interface ItemClickListener with so many events, as many events adapter's views can produce. This solution was written even earlier: https://mcmap.net/q/27176/-how-to-call-a-mainactivity-method-from-viewholder-in-recyclerview-adapter.Sebastiansebastiano
G
12

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));
Geyserite answered 7/11, 2019 at 20:29 Comment(0)
A
5
    There are 2 ways to achieve this 
    
    - In Xml
     <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/list_amenities"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/_8sdp"
                            android:nestedScrollingEnabled="false"                 
 app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
                            app:spanCount="2"
app:layout_constraintEnd_toEndOf="@+id/text_parking_lot_amenities"                       app:layout_constraintStart_toStartOf="@+id/text_parking_lot_amenities"                  app:layout_constraintTop_toBottomOf="@id/text_parking_lot_amenities" />

span count is used for grid columns
- In activity

 listAmenities.layoutManager = GridLayoutManager(this, TWO)
 here TWO indicates number of grid columns
Apodosis answered 9/2, 2022 at 11:3 Comment(0)
P
3

Set in RecyclerView initialization

recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
Peonage answered 1/8, 2020 at 4:50 Comment(1)
How does it differ from other answers?Sebastiansebastiano
S
1

if you want to set grid layout in reyclerview in xml file then you can put these two in in recyclerview xml.

app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount=numberOfItemsInSignleRow

if you want to set grid layout from java code you can write this.

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfItemsInSignleRow));
Salpingectomy answered 2/2, 2022 at 13:22 Comment(0)
D
0

in your MainActivity, where u assigned your recycler view, just use this code.

recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    //recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
Domiciliate answered 20/11, 2021 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.