Saturday 9 September 2017

Android Recyclerview Tutorial | Recyclerview and Cardview Android


Hello warriors whats up guys today i am going to share with you another two  great member of Material family called Recyclerview and Cardview.

If you are not familiar with these widgets then you are wondering about this. so  First of all i am going to give some intro of these two widget.

Recyclerview : 

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerViewwidget when you have data collections whose elements change at runtime based on user action or network eventsformore go to this link...

 CardView : 

CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. for more go to this link...

 I hope now you are not wondering. you can say Recyclerview is an advance version of Listview but its not a Replacement of Listview. Time to start with coding so like each post First of all i will make a module of steps and then we will follow all the step to complete this tutorial.


  1. Create a new project using your android studio File>>New>>New Project. My project name is RecyclerviewDemo you can use your own.
  2. Add Recylerview and CardView dependencies to build.gradle(Module:app).
  3. Add Recylerview to our activity_main.xml and complete this layout.
  4. Create a new layout for single row of Recyclerview using Cardview.
  5. Create an RecylerAdapter java class for Recyclerview by extending RecyclerView.Adapter.
  6. Create a RecylerViewHolder java class for Recyclerview by extending RecyclerView.ViewHolder.
  7. Set Recylerview in MainActivity and complete everything.



1.Create new project :

Open your Android studio and create a new project Go to File>>New>>New project and name it what you want in my case project name is RecyclerViewDemo like below picture.

Leave everything as default and Select Empty Activity from template like below image.


and finish it.

2. Add Recylerview and CardView dependencies to build.gradle(Module:app).

 Go to GradleScripts>>build.gradle(Module:app) and add below libraries to this file under dependencies block like below image.
         compile 'com.android.support:cardview-v7:23.0.1'
         compile 'com.android.support:recyclerview-v7:23.0.1'




after adding dependencies sync your project.

3. Add Recylerview to our activity_main.xml and complete this layout.

Open your activity_main.xml file and add Recyclerview to it . here is my complete activity_main.xml file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?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=".MainActivity">

    <android.support.v7.widget.RecyclerView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:scrollbars="vertical"
         />

</RelativeLayout>


4. Create a new layout for single row of Recyclerview using Cardview:

For single row of Recyclerview i am going to make a simple layout with one imageview and two text for title and description. and complete layout is wrapped inside cardview to give it some good look. here is my item_list.xml 


 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
49
50
51
52
53
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:background="#C5CAE9"
    android:foreground="?attr/selectableItemBackground"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/list_avatar"
        android:layout_width="40dp"
        android:layout_height="40dp"
       android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:scaleType="centerCrop"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/list_title"
        android:layout_centerVertical="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/list_avatar"
        android:text="Androidwarriors "
        android:textColor="#000000"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/list_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/list_title"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/list_avatar"
        android:textColor="#000000"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Place to dive into android programming"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="14sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>


5. Create an RecylerAdapter java class for Recyclerview by extending RecyclerView.Adapter.

So  we have completed all layout stuff now need to do some java code. to connect data set and view we need an adapter as you have  already used adapter in Listview. but in case of Recyclerview we are not going to extend any base adapter or array adapter like Listview. For Recyclerview we are going to extend RecyclerView.Adapter in our Adapter class like below code.Create an new java class by Right click on your package and name it RecyclerAdapterand extend RecyclerView.Adapter it will ask you to implement three method 
  • onCreateViewHolder()
  • onBindViewHolder()
  • getItemCount()
like below code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class RecyclerAdapter extends RecyclerView.Adapter{

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

Now we will complete some small things like we will make an array for title text . we will also make a context variable a LayoutInflater  object and a constructor of Adapter class just copy and paste below code in your adapter class above all the methods.



1
2
3
4
5
6
7
8
9
 String[] name = {"Androidwarriors", "Stackoverflow", "Developer Android", "AndroidHive",
            "Slidenerd", "TheNewBoston", "Truiton", "HmkCode", "JavaTpoint", "Javapeper"};
    Context context;
    LayoutInflater inflater;

    public RecyclerAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }


6.Create a RecylerViewHolder java class for Recyclerview by extending RecyclerView.ViewHolder. 

Right click on your package and create a new java class name it RecyclerViewHolder and extendsRecyclerView.ViewHolder. in this define two textview and an imageview of item_list.xml file. copy and paste below code to your RecyclerViewHolder class. here is my complete code of RecyclerViewHolder.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by androidwarriros on 10/26/2015.
 */
public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView tv1, tv2;
    ImageView imageView;

    public RecyclerViewHolder(View itemView) {
        super(itemView);

        tv1 = (TextView) itemView.findViewById(R.id.list_title);
        tv2 = (TextView) itemView.findViewById(R.id.list_desc);
        imageView = (ImageView) itemView.findViewById(R.id.list_avatar);

    }
}

Now open your RecyclerAdapter and Replace RecyclerView.ViewHolder with RecyclerViewHolder in onCreateViewHolder() and onBindViewHolder(). and inflate item_list.xml file inside onCreateViewHolder(). also make object of RecyclerViewHolder inside onCreateViewHolder and return this object like below code. or simply Replace your onCreateViewHolder() with below code.



1
2
3
4
5
6
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.item_list, parent, false);

        RecyclerViewHolder viewHolder = new RecyclerViewHolder(v);
        return viewHolder;
    }

Now inside onBindViewHolder() method set text to TextView from name array and we will also make onClickListener for click on ImageView of row of RecyclerView. So just copy and Replace your onBindViewHolder() with below code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public void onBindViewHolder(RecyclerViewHolder holder, int position) {

        holder.tv1.setText(name[position]);
        holder.imageView.setOnClickListener(clickListener);
        holder.imageView.setTag(holder);
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            RecyclerViewHolder vholder = (RecyclerViewHolder) v.getTag();
            int position = vholder.getPosition();

            Toast.makeText(context, "This is position " + position, Toast.LENGTH_LONG).show();

        }
    };

One last thing to do in Adapter class is to set number of item or row of RecyclerView so inside getItemCount() method return number of row you want in my case this is length of name array.like below code.


1
2
3
4
@Override
    public int getItemCount() {
        return name.length;
    }

7.Set Recylerview in MainActivity and complete everything.

Open your MainActivity.java and we will complete following steps 
  • Define Recyclerview and register.
  • Make an object of RecyclerAdapter class and set Adapter to Recyclerview.
  • Set Layout Manager to Recyclerview in my case i am using LinearLayoutManager.
 here is my complete code of MainActivity.java just copy and paste this inside your MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);

        RecyclerAdapter adapter=new RecyclerAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);

        //Layout manager for Recycler view
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

0 comments: