Android RecyclerView Tutorial | Custom devider,OnClick listener

Android RecyclerView Tutorial | Custom devider,OnClick listener

Hello guys in this RecyclerView Tutorial I’m going to show you how to add a simple Recyclerview to your android project.I Prefer RecyclerView rather than ListView because it is powerful, flexible and a major enhancement over ListView.

We will learn to create adapter class,POJO class, adding custom list divider and implementing Onclicklistener.This tutorial is made for beginners and intermediates.So lets start by creating new project

1.Creating new project and adding resources

1.Open Android studio and click on File -> new -> new project. now a pop up window appears,add necessary properties for your project and create an empty activity.

2. In the app level build.gradle add the RecyclerView library inside the dependencies tag.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.techpakka.tutorial"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

3. In the styles.xml located inside res->values change Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar for viewing RecyclerView without ActionBar.

4. In the layout file of MainActivity which is activity_main add the following code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
    tools:context=".MainActivity">


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

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

5. Now create a layout file with name recycler_content under res->layout which we will use it to design the content inside RecyclerView. Add the following code.

<?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="wrap_content">
<RelativeLayout
    android:layout_margin="16dp"
    android:background="#56dddddd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/quotes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="&quot;quotes&quot;"
        android:textStyle="italic"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/image"
        android:layout_margin="16dp"/>
    <TextView
        android:id="@+id/author"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Author"
        android:textStyle="bold"
        android:layout_toLeftOf="@+id/image"
        android:layout_alignStart="@+id/quotes"
        android:layout_below="@+id/quotes"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="16dp"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="110dp"
        android:layout_height="110dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_background"
        android:layout_alignParentRight="true"
        android:layout_margin="16dp"/>

</RelativeLayout>
</RelativeLayout>

2. Java code

6. Now we need to create two classes Data class and Adapter class.and add the following code.

Data.java

package com.techpakka.tutorial;

public class Data {
    private String quotes, author;
    private int image;
    public Data(){

    }
    public Data(String quotes,String author,int image){
        this.quotes = quotes;
        this.author = author;
        this.image = image;
    }

    public String getQuotes() {
        return quotes;
    }

    public void setQuotes(String quotes) {
        this.quotes = quotes;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}

Adapter.java

package com.techpakka.tutorial;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{
    private List<Data> list;

    public Adapter(List<Data> list){
        this.list = list;
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView quotes,author;
        public ImageView image;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            author = (TextView) itemView.findViewById(R.id.author);
            quotes = (TextView) itemView.findViewById(R.id.quotes);
            image = (ImageView) itemView.findViewById(R.id.image);

        }
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recycler_content, viewGroup, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        Data data = list.get(i);
        myViewHolder.quotes.setText(data.getQuotes());
        myViewHolder.author.setText(data.getAuthor());
        myViewHolder.image.setImageResource(data.getImage());
    }

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


}

7. So we have created the java files and added the code inside,lets move to the part of creating RecyclerView and adding data.

Add the following code to the MainActivity.java

package com.techpakka.tutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView recycler_view;
    private List<Data> dataList = new ArrayList<>();
    Adapter adapter;

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

        recycler_view = findViewById(R.id.recycler_view);
        adapter = new Adapter(dataList);
        prepareDataData();
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        RecyclerView.LayoutManager horizontalLayoutManager =
                new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recycler_view.setLayoutManager(mLayoutManager);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        recycler_view.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); // add this line to get default divider.
        recycler_view.setAdapter(adapter);

    }

    private void prepareDataData() {
        Data data = new Data("We are all now connected by the Internet, like neurons in a giant brain.", "Stephen Hawkins", R.drawable.hawkins);
        dataList.add(data);

        data = new Data("This is my simple religion. There is no need for temples; no need for complicated philosophy. Our own brain, our own heart is our temple; the philosophy is kindness", "Dalai lama", R.drawable.dalailama);
        dataList.add(data);

        data = new Data("You can't change who you are, but you can change what you have in your head, you can refresh what you're thinking about, you can put some fresh air in your brain.", "Ernesto Bertarelli", R.drawable.ernesto);
        dataList.add(data);

        data = new Data("The chief function of the body is to carry the brain around", "Thomas A Edison", R.drawable.thomas);
        dataList.add(data);

        data = new Data("When you fish for love, bait with your heart, not your brain.", "Mark Twain", R.drawable.mark);
        dataList.add(data);

        data = new Data("I like nonsense; it wakes up the brain cells.", "Dr.Seuss", R.drawable.seuss);
        dataList.add(data);

        data = new Data("Any man who reads too much and uses his own brain too little falls into lazy habits of thinking", "Albert Einstein", R.drawable.einstien);
        dataList.add(data);

        data = new Data("I have a different constitution. I have a different brain; I have a different heart; I got tiger blood, man.", "Charlie Sheen", R.drawable.charlie);
        dataList.add(data);

        data = new Data("Some people say video games rot your brain, but I think they work different muscles that maybe you don't normally use", "Ezra Koenig", R.drawable.ezra);
        dataList.add(data);

        data = new Data("The brain is like a muscle. When it is in use we feel very good. Understanding is joyous", "Carl Sagan", R.drawable.carl);
        dataList.add(data);

        data = new Data("I spend a lot of time upside down. It increases the blood flow to the brain, so it really helps your creativity", "Daphne Guinness", R.drawable.daphne);
        dataList.add(data);

        data = new Data("I'm crazy, I'm nuts. Just the way my brain works. I'm not normal. I think differently.", "Justin Bieber", R.drawable.justin);
        dataList.add(data);

            data = new Data("Non-violence, which is the quality of the heart, cannot come by an appeal to the brain", "Mahatma Gandhi", R.drawable.gandhiji);
        dataList.add(data);

        data = new Data("We are all now connected by the Internet, like neurons in a giant brain.", "Stephen Hawkins", R.drawable.hawkins);
        dataList.add(data);

        adapter.notifyDataSetChanged();
    }
}

t

We have succesfully created our first RecyclerView. test this on the device by clicking on the run button.Now lets implement click action on recycler items.

3.OnClickListener

8. To add OnClicklistener on items in a RecyclerView just add the following code to onBindViewHolder() method in Adapter.java file.

package com.techpakka.tutorial;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{
    private List<Data> list;

    public Adapter(List<Data> list){
        this.list = list;
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView quotes,author;
        public ImageView image;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            author = (TextView) itemView.findViewById(R.id.author);
            quotes = (TextView) itemView.findViewById(R.id.quotes);
            image = (ImageView) itemView.findViewById(R.id.image);

        }
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recycler_content, viewGroup, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        Data data = list.get(i);
        myViewHolder.quotes.setText(data.getQuotes());
        myViewHolder.quotes.setOnClickListener(new View.OnclickListener){
            @Override
            public void OnClick(View view){
                Toast(context,data.getQuotes,TOAST.LENGTH_SMALL).show();
            }
        }
        myViewHolder.author.setText(data.getAuthor());
        myViewHolder.image.setImageResource(data.getImage());
    }

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


}

 

4.Custom Divider

9. Create a new class ItemDecoration.java and add the following code.

package com.techpakka.tutorial;

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

/**
 * Created by Ravi on 30/10/15.
 * updated by Ravi on 14/11/17
 */
public class ItemDecoration 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;
    private Context context;
    private int margin;

    public ItemDecoration(Context context, int orientation, int margin) {
        this.context = context;
        this.margin = margin;
        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 onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        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 + dpToPx(margin), top, right - dpToPx(margin), 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 + dpToPx(margin), right, bottom - dpToPx(margin));
            mDivider.draw(c);
        }
    }

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

    private int dpToPx(int dp) {
        Resources r = context.getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }
}

10.Open the MainActivity.java change the default divider with the newly created one using the following code.

Note: We have added 10dp margin to the divider,like this we can customise our divider with our needs.

package com.techpakka.tutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView recycler_view;
    private List<Data> dataList = new ArrayList<>();
    Adapter adapter;

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

        recycler_view = findViewById(R.id.recycler_view);
        adapter = new Adapter(dataList);
        prepareDataData();
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        RecyclerView.LayoutManager horizontalLayoutManager =
                new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recycler_view.setLayoutManager(mLayoutManager);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        recycler_view.addItemDecoration(new ItemDecoration(this, LinearLayoutManager.VERTICAL, 10));
        recycler_view.setAdapter(adapter);

    }

    private void prepareDataData() {
        Data data = new Data("We are all now connected by the Internet, like neurons in a giant brain.", "Stephen Hawkins", R.drawable.hawkins);
        dataList.add(data);

        data = new Data("This is my simple religion. There is no need for temples; no need for complicated philosophy. Our own brain, our own heart is our temple; the philosophy is kindness", "Dalai lama", R.drawable.dalailama);
        dataList.add(data);

        data = new Data("You can't change who you are, but you can change what you have in your head, you can refresh what you're thinking about, you can put some fresh air in your brain.", "Ernesto Bertarelli", R.drawable.ernesto);
        dataList.add(data);

        data = new Data("The chief function of the body is to carry the brain around", "Thomas A Edison", R.drawable.thomas);
        dataList.add(data);

        data = new Data("When you fish for love, bait with your heart, not your brain.", "Mark Twain", R.drawable.mark);
        dataList.add(data);

        data = new Data("I like nonsense; it wakes up the brain cells.", "Dr.Seuss", R.drawable.seuss);
        dataList.add(data);

        data = new Data("Any man who reads too much and uses his own brain too little falls into lazy habits of thinking", "Albert Einstein", R.drawable.einstien);
        dataList.add(data);

        data = new Data("I have a different constitution. I have a different brain; I have a different heart; I got tiger blood, man.", "Charlie Sheen", R.drawable.charlie);
        dataList.add(data);

        data = new Data("Some people say video games rot your brain, but I think they work different muscles that maybe you don't normally use", "Ezra Koenig", R.drawable.ezra);
        dataList.add(data);

        data = new Data("The brain is like a muscle. When it is in use we feel very good. Understanding is joyous", "Carl Sagan", R.drawable.carl);
        dataList.add(data);

        data = new Data("I spend a lot of time upside down. It increases the blood flow to the brain, so it really helps your creativity", "Daphne Guinness", R.drawable.daphne);
        dataList.add(data);

        data = new Data("I'm crazy, I'm nuts. Just the way my brain works. I'm not normal. I think differently.", "Justin Bieber", R.drawable.justin);
        dataList.add(data);

            data = new Data("Non-violence, which is the quality of the heart, cannot come by an appeal to the brain", "Mahatma Gandhi", R.drawable.gandhiji);
        dataList.add(data);

        data = new Data("We are all now connected by the Internet, like neurons in a giant brain.", "Stephen Hawkins", R.drawable.hawkins);
        dataList.add(data);

        adapter.notifyDataSetChanged();
    }
}

5.Horizontal RecyclerView Tutorial

11. Creating a horizontal RecyclerView is simple.just change the line RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); to

RecyclerView.LayoutManager horizontalLayoutManager =
new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false); 
in MainActivity.java 

and set this layoutmanager for RecyclerView

recycler_view.setLayoutManager(horizontalLayoutManager);    

also don’t forget to change the height of recyclerview to wrap_content in activity_main.java

That’s it for this tutorial i hope you have learned what is RecyclerView and how to implement in our Android Application.If you want more android tutorials just follow my further posts.

%d bloggers like this: