Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)
Clash Royale CLAN TAG#URR8PPP
Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)
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:
RecyclerView
ListView
GridView
RecyclerView
2 Answers
2
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
GridLayoutManager
LinearLayoutManager
RecyclerView
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.
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.
RecyclerView
Update Gradle dependencies
Make sure the following dependencies are in your app gradle.build
file:
gradle.build
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.
RecyclerView
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
TextView
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.
RecyclerView
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
GridView
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
ItemClickListener
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
your grid is not equally disctibuted on the space it has - there is a padding on the right
– Marian Paździoch
Aug 28 '17 at 16:52
@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.
– Suragch
Aug 29 '17 at 1:10
Future readers, let me save you some time, key thing is
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
– daka
Jun 21 at 20:50
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
@daka, good point. I edited my answer to include this in the beginning.
– Suragch
Jun 21 at 23:27
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
onItemClick
MainActivity
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.
onItemClick
MyRecyclerViewAdapter
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:
MyRecyclerViewAdapter.ItemClickListener
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);
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.
– Ahmad Fadli
Mar 27 at 7:18
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
One of the best written answer
– Abhilash Maurya
Jul 21 '17 at 9:53