Android - Material design tutorial -8 ( RecyclerView basics )

Recyclerview was introduced as a replacement of ListView widget. Like listview, recyclerview is also used to display large set of items inside application. But recyclerview is more advanced and efficient than listview.

Introduction :

  • Layout Manager :
  • Layout manager basically defines the types of layout which will be used by recyclerview. Three types of layout managers are available :
  • LinearLayoutManager : Used to display linear list inside RecyclerView
  • GridLayoutManager : Used to display Grids
  • StaggeredGridLayoutManager : Used to display staggered grids (i.e. grids with different heights)
  • ViewHolder :
  • ViewHolder belongs to the adapter of the RecyclerView. This class is used to define a ViewHolder object which is used by the adapter to bind it with a position .It keeps references to all the views of a recyclerview item, which decreses the overhead of creating new references every time an item is displayed.

RecyclerView adapter :

  • RecyclerView adapters are binds with the ViewHolders. This adapter should extend a class called RecyclerView.Adapter passing a class that that implements the ViewHolder patterns. Next we need to override two methods onCreateViewHolderand onBindViewHolderinside the adapter. First one is called when a new instance of the ViewHolder class is created and second one is called when the view is shown in the UI.

ItemDecoration :

  • By default, recyclerView doesnot show any divider between its items. We need to create a custom RecyclerView.ItemDecoration class and it should be linked to the RecyclerView using addItemDecorationmethod.
  1. Create a new sample application on Android Studio.

  2. Add the following gradle dependency on your project’s build.gradle file :

compile 'com.android.support:recyclerview-v7:23.1.1'
  1. Create one Activity MainActivity.java with its corresponding layout as activity_main.xml
public class MainActivity extends AppCompatActivity {

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

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        //create one adapter with a list of 50 elements
        RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getDummyList());
        mRecyclerView.setAdapter(mAdapter);

        //create one item decoration object and add it to the recycler view
        RecyclerView.ItemDecoration dividerItemDecoration =
                new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);


        mRecyclerView.addItemDecoration(dividerItemDecoration);
    }


    private ArrayList<ListModelObject> getDummyList() {
        ArrayList objectList = new ArrayList<ListModelObject>();
        for (int i = 0; i < 50; i++) {
            objectList.add(i, new ListModelObject("Recycler View Item -", i));
        }
        return objectList;
    }
}
<?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"
    tools:context=".activity.MainActivity">

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

</RelativeLayout>
  1. Create an adapter for the RecyclerView :
public class RecyclerViewAdapter extends RecyclerView
        .Adapter<RecyclerViewAdapter
        .ModelObjectHolder> {

    private ArrayList<ListModelObject> mObjectList;


    public RecyclerViewAdapter(ArrayList<ListModelObject> objectList) {
        mObjectList = objectList;
    }

    @Override
    public ModelObjectHolder onCreateViewHolder(ViewGroup parent,
                                                int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_item, parent, false);

        ModelObjectHolder dataObjectHolder = new ModelObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(ModelObjectHolder holder, int position) {
        holder.label.setText(mObjectList.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mObjectList.size();
    }


    //view-holder class
    public class ModelObjectHolder extends RecyclerView.ViewHolder {
        TextView label;

        public ModelObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
        }

    }
}

Here we are using the following layout_item.xml file as layout for RecyclerView 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"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Model Object class for recyclerView item is ListModelObject.java and it looks like as below :

public class ListModelObject {
    private String mName;

    public ListModelObject(String name, int i) {
        this.mName = name + i;
    }

    public String getName() {
        return this.mName;
    }
}
  1. For item Decoration, we are using the DividerItemDecoration class provided by Google :
package com.codevscolor.recyclerviewbasic.util;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };
    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
    private Drawable mDivider;
    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

Run this project and it should be like below :

Animation

In our next tutorial, we will discuss about GridLayoutManager and how to add animation to RecyclerView items.

Source code for this project is available on GitHub . You can pull it from here.