CodeNewbie Community 🌱

Cover image for Implementing a RecyclerView in Android with Java
Tristan
Tristan

Posted on

Implementing a RecyclerView in Android with Java

Introduction

  • This series is going to be where I put all my Android notes. As I learn something new about Android development I will put in this tutorial series

What is a RecyclerView ?

  • Well, essentially a RecyclerView makes is easy and effiecient to display large amounts of data. We supply the data and define how each individual item looks and the RecyclerView library dynamically creates the elements when they're needed

Steps to implement a RecyclerView

  • Implementing a RecyclerView can get confusing, so to makes this easier I have broken things down into 5 easy steps:

1) Add the RecyclerView to an XML file

2) Create individual RecyclerView item XML file

3) Create the ViewHolder

4) Create the Adapter

5) Instantiate the RecyclerView

  • If you are not sure what a ViewHolder or Adapter is, don't worry, we will talk more about them later

1) Add the RecyclerView to an XML file

  • So this part part might be a little confusing, mainly because the name of the library is called RecyclerView and the name of the class is also RecyclerView. So unless I specifically state that we are talking about the library, always assume we are talking about the class. Now add the RecyclerView class to any XML file:
<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         />

Enter fullscreen mode Exit fullscreen mode
  • the layout, width and id are up to the individual developer. Just make sure you are using the proper RecyclerView class.

2) Create individual RecyclerView item XML file

  • As we already know, a RecyclerView is used to display large amounts of data, both easily and efficiently. One of the steps is to define how the individual elements will look. We do that by defining a new XML file, of course the style is up to you. However, I would highly recommend using Android's provided CardView:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp">
        <TextView
            android:id="@+id/text_view_priority"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="154dp"
            android:text="This will get replaced by later" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>
Enter fullscreen mode Exit fullscreen mode
  • Make sure that layout_height of the CardView is set to wrap_content, otherwise you will get REALLY large CardViews.

  • Also, take special note of android:id="@+id/text_view_priority", we are going to use that id later

3) Create the ViewHolder

  • A ViewHolder describes an item view and metadata about its place withing the RecyclerView. Long story short, this class will represent a single item inside the RecyclerView. I would like to point out that the offical tutorial,HERE(and this tutorial also), has the made the ViewHolder class static and nested inside the Adapter class. this is not neccessary, it is mearly done for ease of use purposes. The only restriction on a custom ViewHolder is that it extends the RecyclerView.ViewHolder class. So you can create a ViewHolder class like this:
public static class ViewHolder extends RecyclerView.ViewHolder{
        private  TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            //Define click listener for the ViewHolder's View
            this.textView =  (TextView) itemView.findViewById(R.id.text_view_priority);

        }

        //GETTERS
        public TextView getTextView() {
            return textView;
        }
        //SETTERS
        public void setTextView(TextView textView) {
            this.textView = textView;
        }
    }

Enter fullscreen mode Exit fullscreen mode
  • Notice the TextView and how we are finding its value by R.id.text_view_priority. R.id.text_view_priority is the id from the TextView from step 2. We find Views in this class in order for the Adapter(next step) to bind data to them

4) Create the Adapter

  • Adapters provide a binding from an app-specific data set to views that are displayed within a RecyclerView. The Adapter will work together with the ViewHolder to create individual views and to bind data to those views. The Adapter does this through 3 specific methods:

1) onCreateViewHolder() : RecyclerView(the library not the class) calls this method whenever it needs to create a new ViewHolder. The method creates and initializes the ViewHolder and its associated View but does not fill in the View's contents. So this method's only purpose it to create new instances of our custom ViewHolder from step 3.

@Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //Create a new view, which defines the Ui of the list item
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.indiv_recycler_item,parent,false);
        return new ViewHolder(view);
    }
Enter fullscreen mode Exit fullscreen mode
  • If the LayoutInflater code confuses don't worry. A LayoutInflater's only job is to turn XML code into a View object that our code can interact with. The R.layout.indiv_recycler_item simply means it is using a XML file from the res.layout folder and the XML file is called indiv_recycler_item. The file name should be whatever the file is called that contains the contents of step 2.

2) onBindViewHolder() : RecyclerView library calls this method to associate a ViewHolder with data. The method fetches the appropriate data to fill in the ViewHolder's layout.

@Override 
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.getTextView().setText(localDataSet[position]);
    }
Enter fullscreen mode Exit fullscreen mode

-
the holder object is actually the instantiated ViewHolder object returned from the onCreateViewHolder() method. The only thing I haven't explained is the localDataSet, which I will show later. Right now it is just a simple array any where inside the Adapter class, in the future I will show how to get data from a database.

3) getItemCount() : RecyclerView library calls this method to get the size of the dataset. Very simple and straight forward method:

  @Override
    public int getItemCount() {
        return localDataSet.length;
    }
Enter fullscreen mode Exit fullscreen mode
  • So all together the Adapter class would look something like this:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
    private String [] localDataSet =   {"it","do","be","like","that","sometimes"};



    public static class ViewHolder extends RecyclerView.ViewHolder{
        private  TextView textView;

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

            this.textView =  (TextView) itemView.findViewById(R.id.text_view_priority);

        }

        //GETTERS
        public TextView getTextView() {
            return textView;
        }
        //SETTERS
        public void setTextView(TextView textView) {
            this.textView = textView;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //Create a new view, which defines the Ui of the list item
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.indiv_recycler_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.getTextView().setText(localDataSet[position]);

    }

    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}

Enter fullscreen mode Exit fullscreen mode

5) Instantiate the RecyclerView

  • In this final step we want to do 3 things, 1) find the RecyclerView, 2) set the Adapter, 3) set the layout manager. The only thing that we have not talked about is the LayoutManager so lets do so.

LayoutManager : The layout manager is actually the MVP of the whole RecyclerView library. It determines how the RecyclerView will look, if it is a grid or list. It also determines what items are no longer visual on the screen and how to reuse Views.

  • We have decided to implement a LinearLayoutManager which means that our RecyclerView will look like individual list items.
public class RecyclerViewFragment extends Fragment {
    private RecyclerView recyclerView;


    public RecyclerViewFragment(){
        super(R.layout.recycler_view_fragment);
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState){
        recyclerView = view.findViewById(R.id.recyclerview);
        this.recyclerView.setAdapter(new CustomAdapter());
        this.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


    }


}

Enter fullscreen mode Exit fullscreen mode
  • As you can see the code above is used inside of a fragment, specifically the fragment called R.layout.recycler_view_fragment. However, a RecylerView can also be in an Activity, so you can decided which one to use.
  • With that we have successfully implemented a simple RecyclerView in Android

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Oldest comments (0)