Android RecyclerView with Custom Adapter Example

Posted on: November 15, 2017 at 11:12 am by Sanket Mhaddalkar - No Comments

Android RecyclerView with Custom Adapter Example

 

In this article, will see how to create custom RecyclerView with custom adapter in android. RecyclerView is an advance version of ListView as it has many more features bundled than ListView. As of now, RecyclerView is more preferred over ListView.

 

Steps and Source Code for implementing Custom RecyclerView with Custom Adapter –

 

– First Create a new Project CustomRecyclerViewExample.

 

– Create an empty activity i.e MainActivity.

 

– Now we will add RecyclerView Library to our android project.

 

– Add the following dependency to your app level build.gradle file and Sync the project.

dependencies {

    compile 'com.android.support:recyclerview-v7:27.0.0'
	
}

 

– Now add RecyclerView to your Activity layout file

 

activity_main.xml file:

<?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="com.sanktips.customrecyclerviewexample.MainActivity">

 
<android.support.v7.widget.RecyclerView
android:id="@+id/recycleViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />


</RelativeLayout>

 

– Next step is to create a custom layout file to format how a single row will look in our RecyclerView.

 

– Right click on the layout folder, New and then click on Layout resource file and name it to single_list_item.xml

 

single_list_item.xml file:

<?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:id="@+id/singleRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<ImageView
android:id="@+id/userImg"
android:src="@mipmap/ic_launcher"
android:layout_width="60dp"
android:layout_height="60dp" />

<TextView
android:id="@+id/pNametxt"
android:text="User Name"
android:textSize="20sp"
android:layout_marginTop="6dp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/userImg"
android:layout_toEndOf="@+id/userImg"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" />

<TextView
android:id="@+id/pJobProfiletxt"
android:text="Job Profile"
android:textSize="14sp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/pNametxt"
android:layout_alignLeft="@+id/pNametxt"
android:layout_alignStart="@+id/pNametxt" />

</RelativeLayout>

<View
android:layout_below="@+id/singleRow"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f2f2f2" />


</RelativeLayout>

 

– Now create a simple model class to store the fetched data into objects.

 

PersonUtils.java file:

package com.sanktips.customrecyclerviewexample;


public class PersonUtils {

    private String personName;
    private String jobProfile;

    public PersonUtils(String personName, String jobProfile) {
        this.personName = personName;
        this.jobProfile = jobProfile;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public String getJobProfile() {
        return jobProfile;
    }

    public void setJobProfile(String jobProfile) {
        this.jobProfile = jobProfile;
    }
}

 

– Now we need an adapter to populate data into RecyclerView.

 

– Right click on package folder i.e in my case com.sanktips.customrecyclerviewexample, New and then click on Java Class.

 

– Name the class as CustomRecyclerAdapter and extend it with RecyclerView.Adapter.

 

– Now create a constructor for the class and all overriding methods as given below.

 

CustomRecyclerAdapter.java file:

package com.sanktips.customrecyclerviewexample;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;


public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {

    private Context context;
    private List<PersonUtils> personUtils;

    public CustomRecyclerAdapter(Context context, List personUtils) {
        this.context = context;
        this.personUtils = personUtils;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.itemView.setTag(personUtils.get(position));

        PersonUtils pu = personUtils.get(position);

        holder.pName.setText(pu.getPersonName());
        holder.pJobProfile.setText(pu.getJobProfile());

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{

        public TextView pName;
        public TextView pJobProfile;

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

            pName = (TextView) itemView.findViewById(R.id.pNametxt);
            pJobProfile = (TextView) itemView.findViewById(R.id.pJobProfiletxt);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    PersonUtils cpu = (PersonUtils) view.getTag();

                    Toast.makeText(view.getContext(), cpu.getPersonName()+" is "+ cpu.getJobProfile(), Toast.LENGTH_SHORT).show();

                }
            });

        }
    }

}

 

– Then, Final step to add data to ArrayList and populate it into RecyclerView by setting up the adpater in our MainActivity.

 

MainActivity.java file:

package com.sanktips.customrecyclerviewexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 recyclerView;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager layoutManager;

    List<PersonUtils> personUtilsList;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);

        personUtilsList = new ArrayList<>();

	//Adding Data into ArrayList
        personUtilsList.add(new PersonUtils("Todd Miller","Project Manager"));
        personUtilsList.add(new PersonUtils("Bradley Matthews","Senior Developer"));
        personUtilsList.add(new PersonUtils("Harley Gibson","Lead Developer"));
        personUtilsList.add(new PersonUtils("Gary Thompson","Lead Developer"));
        personUtilsList.add(new PersonUtils("Corey Williamson","UI/UX Developer"));
        personUtilsList.add(new PersonUtils("Samuel Jones","Front-End Developer"));
        personUtilsList.add(new PersonUtils("Michael Read","Backend Developer"));
        personUtilsList.add(new PersonUtils("Robert Phillips","Android Developer"));
        personUtilsList.add(new PersonUtils("Albert Stewart","Web Developer"));
        personUtilsList.add(new PersonUtils("Wayne Diaz","Junior Developer"));

        mAdapter = new CustomRecyclerAdapter(this, personUtilsList);

        recyclerView.setAdapter(mAdapter);

    }
}

 

– Finally we are done with the implementation of RecyclerView with Custom Adapter.

 

Hope you find this article helpful. Join us on Facebook, Twitter and Google+ to get more updates on Android Development Tutorials.

 



About Author:

I am Certified Java Developer. I Develop Android Applications and Websites. I also love blogging so as to share my experiences with others.



Subscribe to our Newsletter

Join our mailing list to receive
the latest news and updates from our team.