Beginning Android Studio 8. Creating a RecyclerView

Introduction

This is the eight article of the Beginning Android Studio series. Last time you learned about ToggleButtons and Switches. In this part, you will learn how to use the RecyclerView. RecyclerViews comes in handy when you need to list certain items in a specific way. In my app, Flashcards, I use RecyclerViews to list folders and cards. Every item share the same XML-layout.

Here's a video of what I will go through in this article if you prefer that, final product at 8:05:

Before we begin however, we need to add a dependency in order to get RecyclerView to work. Navigate to Gradle Scripts -> build.gradle (Module app) in the project tree in Android Studio and add this line:

dependencies {

    // Add this
    implementation 'com.android.support:recyclerview-v7:28.0.0'

}

 

XML

activity_main.xml

Alright, let's begin with telling XML where we want our RecyclerView to display. Open up activity_main.xml and enter:

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

This will make the RecyclerView fill the entire screen. Make sure to give it an id so we can refer to it from our Java code later. That's basically everything we need in our main layout. One thing worth to point out here is that we use androidx in this project. You may come have across an outdated version from the support library:

<android.support.v7.widget.RecyclerView

This is no longer maintained, as stated here, and all new projects should use AndroidX.

 

item_recyclerview.xml

Create a new Layout resource file and name it item_recyclerview. This is going to be the holder for all of our items. In this example I'm just going to use strings as our items, so I'm simply just adding a TextView inside item_recyclerview.xml. This is my full item_recyclerview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#24f">

    <TextView
        android:id="@+id/textview"
        android:layout_gravity="center"
        android:textSize="40sp"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

And that's all we need for the layout. Let's make things happen with Java.

 

JAVA

Now that we have a layout for our strings, we need an adapter to bind our strings to the TextViews we created. So go ahead and create a new Java class, I'm naming mine CustomAdapter:

package com.hallucind.tutorials;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private ArrayList<String> strings;

    public CustomAdapter(ArrayList<String> strings) {
        this.strings = strings;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_recyclerview, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(strings.get(position));
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder{

        public TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textview);
        }
    }
}

 

Quite a few things is going on here. We start by creating a constructor that will take our arraylist of strings as a parameter, and store them globally, so we have something to display:

    private ArrayList<String> strings;

    public CustomAdapter(ArrayList<String> strings) {
        this.strings = strings;
    }

 

At the bottom we create a static subclass called ViewHolder, which extends RecyclerView.ViewHolder: 

    public static class ViewHolder extends RecyclerView.ViewHolder{

        public TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textview);
        }
    }

A ViewHolder describes an item view and metadata about its place within the RecyclerView. This is where we connect the textview with java that we created before in item_recyclerview.xml. We are going to tell the adapter that we want to use that layout soon. The baseclass is using this subclass in its extension:

class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>

This will require us to implement atleast three functions. First, onCreateViewHolder:

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_recyclerview, parent, false);

        return new ViewHolder(view);
    }

In this method, we instansiate our item_recyclerview layout, put it as a parameter to a ViewHolder object, the class we created before, and return the ViewHolder object. See how this is connected? When we created the ViewHolder object we created a constructor that took a View as an argument, and we used this view to find the textview from item_recyclerview. Now we are passing item_recyclerview as a parameter to a ViewHolder, so it will find the correct textview.

The second overriden method is onBindViewHolder:

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(strings.get(position));
    }

This is where we add the strings from our arraylist to the textview. The position argument is the position of the item, which should match with the position in our arraylist. The last method to override is getItemCount,

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

which simply returns the arraylists size.

 

That's it for the adapter, time to open up MainActivity:

package com.hallucind.tutorials;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private CustomAdapter adapter;
    private ArrayList<String> strings;

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

        recyclerView = findViewById(R.id.recyclerview);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        strings = new ArrayList<>();
        strings.add("Horse");
        strings.add("Lion");
        strings.add("Bird");
        strings.add("Train");
        strings.add("Frog");
        strings.add("Cup");
        strings.add("Microwave");

        adapter = new CustomAdapter(strings);
        recyclerView.setAdapter(adapter);
    }
}

We have declared four global things. The RecyclerView, the arraylist of strings, the adapter we just created, and a LayoutManager. In the onCreate method we start with connecting the recyclerview to our main layout. Then we instantiate the layoutManager, and use it to set the recyclerviews layoutmanager. The LayoutManager is responsible for the positioning of our items, we use LinearLayoutManager since we just want a linear vertical scroll.

We add some test values, you probably want to be more creative than me here, and then we instantiate our CustomAdapter and pass the arraylist in as a parameter to CustomAdapters constructor. Finally, we tell the recyclerview to use that adapter with the setAdapter() function.

 

That's all! Run your code and it should display a list of your strings. In the next article, we will figure out how to add a onClickListener to each item so we can interact with them.

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments