Android

RecyclerView With Material Design

Android RecyclerView
Written by Yasir Ameen

RecyclerView is used to create efficient scroll able views similar to listview which is also for best performance. In this tutorial i am going to introduce you RecyclerView widget. The RecyclerView widget is more advanced and flexible version of ListvView. CardView is also a companion of RecyclerView both are introduced in Android lollipop.

In this tutorial i am going to describe you to how to create  Android_RecyclerView widget with rounded border images and some other functionality related to RecyclerView.

 

Let’s Dig In with RecyclerView.

Step 1
Create a project in Android Studio and  give any name you want, I named this RecyclerViewDemo and select Empty Activity.
In order to use RecyclerView_widget you will need to add the

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

dependencies in your build.gradle file.

Dependencies.

In this project i am using the following dependencies,

dependencies {ion of ListV

    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.pkmmte.view:circularimageview:1.1'

}


You will add RecyclerView_widget in your Layout Xml file using the the following snippet.

 


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

 

 

Open activity_main.xml file and add RecyclerView widget, your activity_main.xml file should look like this,

activiy_main.xml

 <?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="yasir.com.recylerdemo.MainActivity">

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

</RelativeLayout>

 

 Step 2 Creating a list_row template.

Create a new Layout Resource file in layout folder and name it list_row.xml and paste the following code.
Note that i am using CircularImageView  for representing Rounded border image.


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

    <com.pkmmte.view.CircularImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img"
        android:src="@drawable/one"
        android:layout_marginLeft="14dp"
        android:layout_marginStart="14dp"
        android:layout_marginTop="12dp"
        app:border="true"
        app:border_color="#EEEEEE"
        app:border_width="2dp"
        app:shadow="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Naturally Flavored Fruit &amp; Herb Detox Water"
        android:id="@+id/txttitle"
        android:textSize="16sp"
        android:layout_marginLeft="15dp"
        android:lines="1"
        android:paddingTop="10dp"
        android:ellipsize="marquee"
        android:layout_alignTop="@+id/img"
        android:layout_toRightOf="@+id/img"
        android:layout_toEndOf="@+id/img" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="This tasty brew only takes ten minutes to prepare."
        android:id="@+id/txtdesc"
        android:layout_marginRight="15dp"
        android:lines="2"
        android:paddingBottom="10dp"
        android:ellipsize="end"
        android:layout_below="@+id/txttitle"
        android:layout_alignLeft="@+id/txttitle"
        android:layout_alignStart="@+id/txttitle" />

</RelativeLayout>

 

Step 2 Creating a Adapter class .

Create a new class MoviesAdapter and extend it to RecyclerView.Adapter class and implement the following Methods in you class.

1) onCreateViewHolder{ … }   // Create new views (invoked by the layout manager
2) onBindViewHolder{ … }    //  Replace the content of view
3) getItemCount{ … }             //   Return the size of your dataset

all the methods will be implemented  in your class by hitting Alt + Enter placing the cursor in red underline of the class declaration.
I am using static data for this project, so i am using String arrays for the title, description and int array for the references of drawable resources.


/**
 * Created by Yasir Ameen on 1/26/2016.
 */
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.myViewHolder> {

    private final LayoutInflater inflater;
    String[] title = {

            "The Shawshank Redemption",
            "The Godfather",
            "The Dark Knight",
            "Schindler's List",
            "Fight Club",
            "Inception",
            "The Matrix",
            "The Silence of the Lambs",
            "Life Is Beautiful",
            "Interstellar"

    };

    final String[] desc = {

            "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. ",
            "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
            "In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.",
            "The masterful concoction features a delicious core of mandarin oranges",
            "An insomniac office worker, looking for a way to change his life, crosses paths with a devil-may-care soap maker, forming an underground fight club that evolves into something much, much more",
            "A thief who steals corporate secrets through use of the dream-sharing technology is given the inverse task of planting an idea into the mind of a CEO.",
            "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
            "A young F.B.I. cadet must confide in an incarcerated and manipulative killer to receive his help on catching another serial killer who skins his victims.",
            "When an open-minded Jewish librarian and his son become victims of the Holocaust, he uses a perfect mixture of will, humor and imagination to protect his son from the dangers around their camp.",
            "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival."

    };

    int[] images = {
            R.drawable.one,
            R.drawable.two,
            R.drawable.three,
            R.drawable.four,
            R.drawable.five,
            R.drawable.six,
            R.drawable.seven,
            R.drawable.eight,
            R.drawable.nine,
            R.drawable.ten

    };

    public MoviesAdapter(Context context, String[] object){
        inflater = LayoutInflater.from(context);
        this.title = object;
    }
    @Override
    public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.list_row,parent,false);
        myViewHolder holder = new myViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(myViewHolder holder, int position) {

        holder._title.setText(title[position]);
        holder._desc.setText(desc[position]);
        holder._imgview.setImageResource(images[position]);
    }

    @Override
    public int getItemCount() {
        return title.length;
    }

   public class myViewHolder extends RecyclerView.ViewHolder {

       ImageView _imgview;
       TextView  _title;
       TextView _desc;

        public myViewHolder(View itemView) {

            super(itemView);
            _imgview = (ImageView) itemView.findViewById(R.id.img);
            _title = (TextView) itemView.findViewById(R.id.txttitle);
            _desc = (TextView) itemView.findViewById(R.id.txtdesc);
        }
    }
}

 

Step 3 .

After creating a Adapter class for recyclerView open your MainActivity.java and paste the following code.


public class MainActivity extends AppCompatActivity {

    String[] title = {

            "The Shawshank Redemption",
            "The Godfather",
            "The Dark Knight",
            "Schindler's List",
            "Fight Club",
            "Inception",
            "The Matrix",
            "The Silence of the Lambs",
            "Life Is Beautiful",
            "Interstellar"

    };

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

        MoviesAdapter adpater = new MoviesAdapter(MainActivity.this, title);
        RecyclerView rview = (RecyclerView) findViewById(R.id.my_recycler_view);
        rview.setItemAnimator(new DefaultItemAnimator());
        rview.setAdapter(adpater);
        rview.setLayoutManager(new LinearLayoutManager(MainActivity.this));

 }

}

Run the application and you will see the results like this, initially you will not see any divider or separator. You will have to implement it using the RecyclerView.ItemDecoration class.

android RecycleView

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Step 4 Decorating items.

RecyclerView_widget do not have any attribute or property for setting separator or divider, you have to implement it using RecyclerView.ItemDecoration abstract class but first create a drawable for divide

1) Create a drwable xml file and name it line_divider.xml and paste the following code.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="1dp"
        android:height="1dp" />

    <solid android:color="#cccccc" />

</shape>

2) Create a class and call it DividerItemDecoration and extend the class to RecyclerView.ItemDecoration and past the following code.


public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.line_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}

Now Open MainActivity.java file and add the following line before set adapter.


rview.addItemDecoration(new DividerItemDecoration(getApplicationContext()));
...
rview.setAdapter(adpater);
rview.setItemAnimator(new DefaultItemAnimator());
rview.setLayoutManager(new LinearLayoutManager(MainActivity.this));

layout-2016-01-27-161724sdfy

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

External Resources

if you want to learn more about Recycler View please goto the following link.

Android Recycler and CardView .

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

5 Comments

Leave a Comment