How to Create a RecyclerView in Android

Tiempo de lectura: 3 minutos

Reading time: 3 minutes

Hello everyone, this time I want to show you how to create a RecyclerView in Android.

List created with RecyclerView

A RecyclerView allows us to efficiently create a list interface in Android. This object can build a composite view of multiple elements given an input list or array. It also performs intelligent memory management, keeping only the elements that are visible on the screen and recycling those that are not.

A RecyclerView is composed of:

  • An Activity where we display the RecyclerView.
  • A RecyclerView Adapter.
  • A ViewHolder that assigns the XML or layout to the RecyclerView.
  • A Layout that represents the view of a single item (row) in the RecyclerView.

Let’s start by creating the Activity with the layout that contains our RecyclerView, and we’ll name it RecyclerActivity:

public class RecyclerActivity extends AppCompatActivity {

 private RecyclerView recyclerView;

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

       recyclerView = findViewById(R.id.recyclerView);
 }
 
}

In this code, we have created and assigned the recyclerView attribute of type RecyclerView.

Now let’s create the view that contains the RecyclerView, and we’ll name it recycler_activity.xml:

<?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">

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

</RelativeLayout>

We have created a RecyclerView with the ID recyclerView. Additionally, we have set it to occupy the entire screen with the following attributes:

android:layout_width="match_parent"
android:layout_height="match_parent"

Once we have created the Activity where we will display our list, we need to create the elements that handle the RecyclerView.

First, we create the layout that represents a row in the list, and we’ll name it recycler_row.xml:

<?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"
    android:id="@+id/capa_row"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:orientation="horizontal">
                       
   <TextView
     android:id="@+id/textoElementoLista"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_gravity="center"/>

</RelativeLayout>
  

We have created this layout with a TextView inside, where we will fill in the name of the element in our list.

Now let’s create a Java class that serves as the ViewHolder, and we’ll name it RecyclerViewHolder:

// View holder to handle the view
public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    public TextView textoElementoLista;

    public RecyclerViewHolder(View itemView) {
        super(itemView);
            textoElementoLista= itemView.findViewById(R.id.textoElementoLista);
    }
}

The class we created extends RecyclerView.ViewHolder and is used to assign the elements of the layout that represents a row in the list.

It contains a RecyclerViewHolder constructor that takes a View (where the layout we created will be).

To assign the variable to the view element, we use itemView.findViewById()

Additionally, the variables we want to use should always be public.

Once the ViewHolder is created, we need to create the RecyclerView Adapter. To do this, we createla siguiente clase, which you can call ManejadorRecyclerView.class:

public class ManejadorRecyclerView extends RecyclerView.Adapter<RecyclerViewHolder> {

    private List<String> lista;

    public ManejadorRecyclerView(List<String> lista) {
        this.lista= lista;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
       View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
        return new RecyclerViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int position) {
        final String elementoActual = lista.get(position);
        holder.textoElementoLista.setText(elementoActual);
    }

    @Override
    public int getItemCount() {
        if (lista != null) {
            return lista.size();
        } else {
            return 0;
        }
    }
}

In the above code, we first extend RecyclerView.Adapter<RecyclerViewHolder> to indicate that it uses the RecyclerViewHolder as the ViewHolder class we created in the previous step.

We pass the list of elements to the constructor of the ManejadorRecyclerView class.

In the onCreateViewHolder method, we assign the layout we created for each item in the list from the previous step, recycler_row.xml:

View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);

Then, we have the onBindViewHolder method, which is called when the item in the list appears on the screen and is “drawn” by the Android interface on the device. In this method, we create and assign the graphic elements of the view to benefit from the memory management provided by RecyclerView. Here, we assign the String from the list to the TextView in our layout using the line holder.textoElementoLista.setText(elementoActual); where we use holder. to refer to the previous ViewHolder.

Finally, the getItemCount() method returns the current position in the list.

Now we just need to assign all the created classes within the Activity with the following code:

public class RecyclerActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

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

        recyclerView = findViewById(R.id.recyclerView);

        // Example list
        List<String> lista = new ArrayList<>();
        lista.add("Test 1");
        lista.add("Test 2");
        lista.add("Test 3");

        // Assign the adapter to the RecyclerView
        ManejadorRecyclerView adapter = new ManejadorRecyclerView(lista);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    }
}

First, we create an example list of strings:

List<String> lista = new ArrayList<>();
lista.add("Test 1");
lista.add("Test 2");
lista.add("Test 3");

Then, we create the ManejadorRecyclerView:

ManejadorRecyclerView adapter = new ManejadorRecyclerView(lista);

And we assign the adapter to the RecyclerView:

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);

And that’s the end of today’s tutorial on how to create a RecyclerView in Android to display our lists.

Leave a Comment