Android RecyclerView

Android RecyclerView

Android RecyclerView Example – In this tutorial you will learn following terms it will take too much time this chapter is long so be patient and love to read,think and code!

android recyclerview

  • 1. What is Android RecyclerView?
  • 2. Android RecyclerView Example
    • 2.1. Creating Android Project
    • 2.2. Declaring Android Activity Layout
    • 2.3. Android RecyclerView Row Layout
    • 2.4. Creating RecyclerView Adapter
    • 2.5. Activity Using RecyclerView
  • 3. Handle RecyclerView Click Event

So we starts from zero.

What Is Android RecyclerView?

In Google android 5.0 Lollipop, Android os unveiled android RecyclerView widget. Android RecyclerView is adaptable and effective version of ListView. It really is an pot for rendering much larger data group of views that may be recycled and scrolled very successfully. Android RecyclerView is similar to traditional ListView widget, but with an increase of overall flexibility to customizes and optimized to utilize greater datasets. It runs on the subclass of RecyclerView.Adapter for providing views that symbolize items in a data set in place.

Android os SDK doesn’t includes the RecyclerView class. You need to include the next support collection graddle dependency to task build.graddle file.

compile ''


This guide clarifies how to use and personalize Android RecyclerView in Android os applications.

Android RecyclerView Example

Throughout this android recyclerview example we will download the info from JSON API, parse and screen the things on RecyclerView. As possible notice in the next image, we are using both RecyclerView and CardView for creating the app ui

Following steps must complete the android recyclerview example:

  1. Create a fresh Android Request and add the mandatory graddle dependencies
  2. Structure activity and add RecyclerView and ProgressBar
  3. Layout the RecyclerView row  item using CardView widget
  4. Develop a Custom Adapter for RecyclerView
  5. Create main Activity to initialize UI, make HTTP Server get and render data on RecyclerView
  6. Giving an answer to RecyclerView click event

Creating Android os Project

Let us get started with creating a fresh Android job in Android Studio. After the task is created, wide open app build.graddle file and add the next dependency libraries.

dependencies {
    compile ''
    compile ''
    compile 'com.squareup.picasso:picasso:2.5.2'
    // ...


Notice that, we’ve added RecyclerView, CardView support libraries and Picasso dependency component.

Picasso can be an Start Source image loader catalogue created and preserved by Square. It really is one of the powerful image download and caching catalogue for Android.

Adding Internet Agreement:

<uses-permission android:name="android.permission.INTERNET" />


Declaring Activity Layout

Why don’t we now explain the design for Activity. We will put in a RecyclerView and ProgressBar in the RelativeLayout. The improvement pub will be viewed as the data data from REST API has been downloaded.

Create a fresh document activity_main.xml inside design source folder and paste the next snippets.

<?xml version="1.0" encoding="utf-8"?>




 Android RecyclerView Row Layout

Within the example, each row item is displayed by way of a CardView that hosts a RelativeLayout with an ImageView for the thumbnail and a TextView subject. This structure resides in the record list_row.xml.

<?xml version="1.0" encoding="utf-8"?>





 Creating Android RecyclerView Adapter

Android os RecyclerView includes special kind of adapter which works just about identical to traditional Android osadapters but with additional functionalities.It runs on the subclass of RecyclerView.Adapter for providing views that signify items in a data place.The excess functionalities of RecyclerView.Adapter are:

It offers two new methods like onCreateViewHolder() and onBindViewHolder() to arrange the code. You need to override both of these options for inflate the view and bind data to the view

Implements a ViewHolder by default. Conceptually RecyclerView.ViewHolder works identical to the ViewHolder design routine which we’ve been using with other Adapters. Manages the over head of recycling and provides better performance and scrolling

Create a fresh new class MyRecyclerViewAdapter.class and copy the next snippets.

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
    private List<FeedItem> feedItemList;
    private Context mContext;

    public MyRecyclerViewAdapter(Context context, List<FeedItem> feedItemList) {
        this.feedItemList = feedItemList;
        this.mContext = context;

    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;

    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
        FeedItem feedItem = feedItemList.get(i);

        //Render image using Picasso library
        if (!TextUtils.isEmpty(feedItem.getThumbnail())) {

        //Setting text view title

    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);

    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView imageView;
        protected TextView textView;

        public CustomViewHolder(View view) {
            this.imageView = (ImageView) view.findViewById(;
            this.textView = (TextView) view.findViewById(;


Notice that we’ve created an private ViewHolder category. The ViewHolder class contains the mention of the each one of the ui widget on the row.the FeedItem class can be an model class that retains the parsed data retrieved from JSON API. Put in a new new data file class in assembling your project source folder and add the next.

public class FeedItem {
    private String title;
    private String thumbnail;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public String getThumbnail() {
        return thumbnail;

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;

 Activity Using Android RecyclerView

The causing RecyclerView implementation because of this example application contains MainActivity initialization code. MainActivity creates the mRecyclerView case, download and parse the info from JSON API, instantiates the adapter and plugs in the adapter to RecyclerView.

The focus of the tutorial is small right down to RecyclerView, hence it generally does not include any reason for download and parse data from server.Once data is downloaded, inside onPostExecute() we live initializing the adapter and establishing adapter to RecyclerView case by just dialling setAdapter() method.

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "RecyclerViewExample";
    private List<FeedItem> feedsList;
    private RecyclerView mRecyclerView;
    private MyRecyclerViewAdapter adapter;
    private ProgressBar progressBar;

    protected void onCreate(Bundle savedInstanceState) {

        mRecyclerView = (RecyclerView) findViewById(;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        progressBar = (ProgressBar) findViewById(;

        String url = "";
        new DownloadTask().execute(url);

    public class DownloadTask extends AsyncTask<String, Void, Integer> {

        protected void onPreExecute() {

        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            return result; //"Failed to fetch data!";

        protected void onPostExecute(Integer result) {

            if (result == 1) {
                adapter = new MyRecyclerViewAdapter(MainActivity.this, feedsList);
            } else {
                Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("posts");
            feedsList = new ArrayList<>();

            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                FeedItem item = new FeedItem();
        } catch (JSONException e) {

 Handle of RecyclerView Click Event

Handling/Managing click event on RecyclerView is much less easy as controlling click listener in ListView or GridView. Android os RecyclerView doesn’t provide any built-in listeners or helpful way of managing click events.

why don’t we declare a app  that specifies listener’s action. When consumer clicks on the RecyclerView the listener will go back the FeedItem for the decided on row.

public interface OnItemClickListener {
    void onItemClick(FeedItem item);


Now start to adapter and declare an example variable of OnItemClickListener along with getter and setter methods.

private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
    return onItemClickListener;

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;


In activity class, let arranged the click listener to adapter by contacting setOnItemClickListener() method.

adapter.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(FeedItem item) {
        Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_LONG).show();



Now, add the View.OnClickListener to each one of the view you want to take care of click. Add the next snippet to onBindViewHolder of the RecyclerView.Adapter. When ImageView or TextView is clicked, we will have the event back again to the caller activity.

View.OnClickListener listener = new View.OnClickListener() {
    public void onClick(View v) {

Here Our Tutorial Ends! 🙂

See Also:

Android ListView

Android CardView

Android RelativeLayout