Twitter LogoFacebook Logo
RecyclerView
The RecyclerView is view that we can scroll vertically or horizontally across the screen while displaying one or more views at a time.
By: King Wai Mark

The RecyclerView is view that we can swipe vertically or horizontally across the screen to slide through views of data.

Unlike the ListView, the RecyclerView is meant to display large amount of data. This is because in a ListView, if there are 50 items you want to display, all 50 items must be ready to go from the start.


In a RecyclerView, the system will only display the necessary amount of views it needs to fill the screen. Then as you swipe, it will recycle the views and repopulate the data in each view that is visible. 

Components

There are a couple of components that you will need.

(1) the RecyclerView
(2) a layout for the placeholder views
(3) an adapter to filter the data that is coming

Setting Up

To begin, go into the app level build gradle file and implement the RecyclerView.

dependencies {
    ...

    def version = "1.1.0"
    implementation "androidx.recyclerview:recyclerview:$version"

}

For the latest version, visit the android developer website.

Go into a xml layout file and add the RecyclerView. Remember to switch to the Design view. In the palate, search for RecyclerView, and drag the view into the layout.

Image from Codeible.com

I am using the Constraint layout so I need to add the constraints. If you are using any other layouts, make sure to set the width and height of the RecyclerView so it will be visible.

Image from Codeible.com

Lastly, give the RecyclerView an id.

Image from Codeible.com

Writing the Code

Next, go into the class file that is using the layout and create a variable reference for the RecyclerView.

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;

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

        myRecyclerView = findViewById(R.id.myRecyclerView);

    }
}

Create the Adapter

Then create the adapter. Define a new class definition and have it extend the Adapter class from RecyclerView. 

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    }

    class RecyclerViewAdapter extends RecyclerView.Adapter<>{


    }

}

There are 2 parts to the adapter. 

(1) The adapter itself, which is used to accept data
(2) The View Holder. The view holder represents the individual view for the RecyclerView. When the adapter takes in data, it will pass it into the view holder and the view holder will filter the data and then place them in the correct place for the view.

We can ignore the error for now. 

There is an error because we have to put in a View Holder class inside the angle brackets of the adapter declaration.

To create the View Holder class, define a new class inside the adapter class and have it extend ViewHolder from RecyclerView.

public class MainActivity extends AppCompatActivity {

    class RecyclerViewAdapter extends RecyclerView.Adapter<>{

        class RecyclerViewViewHolder extends RecyclerView.ViewHolder{


        } // View Holder

    }  // Adapter

} // Main Activity

Then hover over the View Holder class definition, click on the red lightbulb icon, and select the "Create constructor matching super" option.

Image from Codeible.com

This will create the constructor that we need to finish the View Holder class.

Once we have basic View Holder is completed, we can place it inside the angle brackets of the adapter.

public class MainActivity extends AppCompatActivity {

    class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewViewHolder >{

        class RecyclerViewViewHolder extends RecyclerView.ViewHolder{


        } // View Holder

    }  // Adapter

} // Main Activity

Then we have to implement the necessary methods for the adapter. Hover over the adapter class definition, click on the red light bulb icon, and the select "Implement Methods" option.

Image from Codeible.com

@NonNull
@Override
public RecyclerViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     return null;
}

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

}

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

The onCreateViewHolder() method is used to create the individual views for the RecyclerView.

The onBindViewHolder() method is used link the data with the view of the view holder so it can place the data in the correct place.

And the getItemCount() method represents how many items there are.

Defining the View for the View Holder

Next, create an xml layout file for the View Holder. Select the Android option from them drop down menu. Right click on the res folder and go to new > Android Resource File.

Image from Codeible.com

Give the file a name and select "Layout" for the Resource type.

Image from Codeible.com

This layout file will represent the individual views for the RecyclerView. 


Swap to the Code view and change the layout to Linear and set the orientation to vertical. 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"

>
</LinearLayout>

Swap back to the design view and add 2 TextViews.

Image from Codeible.com

Call the first TextView view_title and set the font size to 18sp so it will be larger than the other one. Then call the second one view_subtitle.

Lastly, set the height of the linear layout to wrap content.

Image from Codeible.com

Defining a Class for our Data

Define a class for your data. 

Right click on the project directory and go to New > Java Class or Kotlin File if you are using Kotlin. Name it NewsArticle. 

Image from Codeible.com

For this class, we will have 2 String variables – title and subtitle. Then define a constructor and mutator methods for each variable.

public class NewsArticle {
    private String title;
    private String subtitle;

    public String getTitle() {
        return title;
    }

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

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public NewsArticle(String title, String subtitle) {
        this.title = title;
        this.subtitle = subtitle;
    }
}

Putting it all together

Go back to the class file where you have your adapter. Define an ArrayList for the data class and populate it with some items.

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;

    private ArrayList<NewsArticle> newsArticles = new ArrayList<>();

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

        for(int i = 0; i < 20; i++){
            newsArticles.add(
                    new NewsArticle("title " + i, "subtitle " + i)
            );
        }

        myRecyclerView = findViewById(R.id.myRecyclerView);

    }

    class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewViewHolder >{

        class RecyclerViewViewHolder extends RecyclerView.ViewHolder{


        } // View Holder

    }  // Adapter

}


In the onCreateViewHolder() method of the adapter, we want to return a new view holder object.


Pass in the layout file that we created for the view holder. Call LayoutInflator dot from and pass in the context from the parent object

Then call the inflate method. Pass in the id for the layout file, then the view group, and false for the last argument. We put false because the view will get attached to the root automatically.

@NonNull
@Override
public RecyclerViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new RecyclerViewViewHolder(LayoutInflater.from(parent.getContext())
            .inflate(R.layout.view_holder_view, parent, false));
}

In the getItemCount() method, return the size of the array with our data.

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

In the ViewHolder class, declare a reference for the 2 TextViews in the view holder layout.

Then create a method call link(). For the parameter, it will take in a news article object. 


Inside the method, set the title TextView value to the value of the title variable in the news article object. Then do the same for the subtitle.

class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
     private TextView tvTitle, tvSubtitle;

     public RecyclerViewViewHolder( View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.view_title);
            tvSubtitle = itemView.findViewById(R.id.view_subtitle);
     }

     public void link(NewsArticle newsArticle){
             tvTitle.setText(newsArticle.getTitle());
             tvSubtitle.setText(newsArticle.getSubtitle());
      }

}

In the onBindViewHolder() method of the adapter, call the link() method and pass in a news article object from the array using the position argument.

@Override
public void onBindViewHolder(RecyclerViewViewHolder holder, int position) {
   holder.link(newsArticles.get(position));
}

Then add the adapter to the RecyclerView. Call the setAdapter() method and pass in the adapter.

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;

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

        myRecyclerView = findViewById(R.id.myRecyclerView);
        myRecyclerView.setAdapter(new RecyclerViewAdapter());

    }
}

Lastly, set the layout that you want to use by calling the setLayoutManager() method. With this method, we can set how we want to arrange the items inside.

We can use a LinearLayoutManager, which arranges the items in a single stream horizontally or vertically.

GridLayoutManager which arranges the items in a grid-like fashion.

Or a StaggeredGridLayoutManager which is similar to the GridLayoutManager but each items in the grid has their own width and height.

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
myRecyclerView.setLayoutManager(linearLayoutManager);

Changing the Orientation

To change the orientation to horizontal, we can call the setOrientation() method from the LinearLayoutManager and set it to horizontal.

linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);


Sign In