ZOFTINO.COM

RecyclerView and GridLayoutManager Example

RecyclerView items can be displayed in a grid using GridLayoutManager. In this post, I’ll show how to use RecyclerView and GridLayoutManager.

To know basics about RecyclerView, you can read my previous post on Recycler View.

Below are details of all the required components for recycler view and grid layout manager example. This example is one of the screen in coupons apps which displays list of stores.

RecyclerView Item Layout Using ConstraintLayout

As you know RecyclerView is used to display list of items. So we need to define layout for each item. Let’s use ConstraintLayout to define RecyclerView item layout for this example as there are five widgets with different positional and alignment requirement and using ConstraintLayout improves UI performance. If you want to know more about constraint layout, read my previous post on constraint layout examples.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/storeImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/arrow_up_float"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></ImageView>

    <Button
        android:id="@+id/viewCpnB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/storeImg"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"></Button>

    <TextView
        android:id="@+id/cpnCntT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toRightOf="@+id/viewCpnB"
        android:layout_marginLeft="8dp"
        app:layout_constraintBaseline_toBaselineOf="@+id/viewCpnB"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></TextView>

    <Button
        android:id="@+id/viewCbB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/viewCpnB"
        android:layout_marginLeft="8dp"
        android:layout_marginBottom="24dp"
        app:layout_constraintLeft_toLeftOf="parent"></Button>

    <TextView
        android:id="@+id/maxCbT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toRightOf="@+id/viewCbB"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@+id/viewCbB"></TextView>
</android.support.constraint.ConstraintLayout>

RecyclerView ConstraintLayout Output

Below is the output screen with recycler view, constraint layout, and grid layout manager in vertical orientation.

recycler view and constraint layout example

Activity Layout

 <LinearLayout 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"
    tools:context="com.zoftino.androidui.ActivityRecyclerViewGrid">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/store_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"></android.support.v7.widget.RecyclerView>
</LinearLayout>
 

RecyclerView Adapter

In RecyclerView, adapter binds data to view. Below is the explanation of adapter for our example, which binds store data to views in the item layout.

RecyclerView adapter is created by extending RecyclerView.Adapter. RecyclerView adapter needs a list of data items to be displayed in recycler view and context, which are passed to its constructor.

private List<ZoftinoStore> storesList;
private Context context;

public ZoftinoStoreAdapter(List<ZoftinoStore> stLst, Context ctx) {
    storesList = stLst;
    context = ctx;
}

ViewHolder class is defined in RecyclerView adapter. The nested view holder class is used to hold reference to views in recycler view item layout. When ViewHolder is instantiated, root view of recyclerview’s item layout is passed to constructor.

Click events can be handled by defining click event listeners. For our example, there are three click events that are handled separately to take different action. This example shows how to handle click event at RecyclerView item level and it also shows how to handle click events of child views in RecyclerView item.

 public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView maxCashback;
    public TextView totalCoupons;
    public ImageView storeImg;

    public ViewHolder(View view) {
        super(view);
        maxCashback = (TextView) view.findViewById(R.id.maxCbT);
        totalCoupons = (TextView) view.findViewById(R.id.cpnCntT);
        storeImg = (ImageView) view.findViewById(R.id.storeImg);

        Button viewcb = (Button) view.findViewById(R.id.viewCbB);
        Button viewcpn = (Button) view.findViewById(R.id.viewCpnB);

        view.setOnClickListener(this);

        viewcb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You view Cashback button for item position "+ getAdapterPosition(),
                        Toast.LENGTH_LONG).show();
            }
        });
        viewcpn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You view coupons button for item position "+ getAdapterPosition(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, "You store item for item position "+ getAdapterPosition(),
                Toast.LENGTH_LONG).show();
    }
}

RecyclerView calls createViewHolder method of recycler view adapter which in turn calls onCreateViewHolder method. Below is the implementation of onCreateViewHolder method, which inflates item layout, passes it to view holder and returns the view holder object to recycler view.

 @Override
public ZoftinoStoreAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclergrid_item, parent, false);

    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}
 

RecyclerView calls bindViewHolder method of recycler view adapter, which in turn calls onBindViewHolder method. This method populates the given view holder with item data from items list for the given position.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ZoftinoStore store = storesList.get(position);
    holder.maxCashback.setText(store.getMaxCashback());
    holder.totalCoupons.setText(store.getCouponCount());
    holder.storeImg.setImageResource(store.getStoreImg());
}

Activity

In the activity onCreate method, GridLayoutManager and RecyclerView Adapter are set to RecyclerView. GridLayoutManager offers different constructors which allow you to specify how items will be displayed in RecyclerView.

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

    rv = (RecyclerView) findViewById(R.id.store_rv);

    GridLayoutManager gridlm = new GridLayoutManager(this, 2);
    rv.setLayoutManager(gridlm);
    ArrayList<ZoftinoStore> al = CouponStoreData.getStoreData();
    ZoftinoStoreAdapter rvadapter = new ZoftinoStoreAdapter(al,this);
    rv.setAdapter(rvadapter);
}
 

GridLayoutManager Orientation

RecyclerView items can be displayed in horizontal or vertical orientation by setting the orientation property of GridLayoutManager with setOrientation method. Below is the output when orientation is set to GridLayoutManager.HORIZONTAL.

recyclerview and gridlayoutmanager example

GridLayoutManager SpanCount

With GridLayoutManager, number of rows in horizontal orientation or number of columns in vertical orientation can be configured by setting spancount with setSpanCount method. Below screen shows that RecyclerView items are displayed in three rows.

recycler view and grid layout manager spancount example