[For beginners] Minimum sample to display RecyclerView in Java

Introduction

When displaying a list of reusable views on Android, a widget called RecyclerView is the mainstream. But at first, multiple parts came out and I wasn't sure, so I'll make a minimum sample.

↓ Completed image Screenshot_1588515747.png

Preparation

Add RecyclerView to build.gradle.


dependencies {
    implementation "androidx.recyclerview:recyclerview:1.1.0"

Character

Steps to display

  1. Create layout file for RecyclerView
  2. Create layout for ViewHolder (one line of list)
  3. Create Adapter / ViewHolder
  4. Generate RecylerView with Activity

Let's look at each one.

1. Create layout file for RecyclerView

Place the RecyclerView on top of the Activity for which you want to display the RecyclerView. (If you want to use fragments, the same is true for fragments.)

スクリーンショット 2020-05-03 22.08.58.png
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

2. Create layout for ViewHolder (one line of list)

Next, make a layout for one line. This time I will make it like this. This depends on the content of the list you want to make.

スクリーンショット 2020-05-03 22.24.24.png
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="12dp">

    <ImageView
        android:id="@+id/hoge_image_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

    <TextView
        android:id="@+id/hoge_title_text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:text="hogeTitle"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="@id/hoge_image_view"
        app:layout_constraintStart_toEndOf="@id/hoge_image_view"
        app:layout_constraintEnd_toEndOf="parent"/>

    <TextView
        android:id="@+id/hoge_contents_text_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="hogeContents"
        android:layout_marginTop="12dp"
        app:layout_constraintTop_toBottomOf="@id/hoge_title_text_view"
        app:layout_constraintStart_toStartOf="@id/hoge_title_text_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

3. Create Adapter / ViewHolder

After that, the order doesn't really matter, but this time we will prepare the Adapter first. This is because a set of Adapters is required when generating a RecyclerView.


public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
    
    private List<RowData> rowDataList;

    MainAdapter(List<RowData> rowDataList) {
        this.rowDataList = rowDataList;
    }

    /**
     *One line of data
     */
    static class MainViewHolder extends RecyclerView.ViewHolder {
        ImageView hogeImage;
        TextView hogeTitle;
        TextView hogeContents;

        MainViewHolder(@NonNull View itemView) {
            super(itemView);
            hogeImage = itemView.findViewById(R.id.hoge_image_view);
            hogeTitle = itemView.findViewById(R.id.hoge_title_text_view);
            hogeContents = itemView.findViewById(R.id.hoge_contents_text_view);
        }
    }

    /**
     *ViewHolder method
     *Only called first.
     *Here, the ViewHolder that generated the ViewHolder layout file as inflation is returned to the RecyclerView.
     */
    @NonNull
    @Override
    public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_main, parent, false);
        return new MainViewHolder(view);
    }

    /**
     *Bind ViewHolder and RecyclerView
     *Write here the processing that you want to do in common for one line of View. This time I only set the text.
     */
    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        RowData rowData = this.rowDataList.get(position);
        holder.hogeTitle.setText(rowData.hogeTitle);
        holder.hogeContents.setText(rowData.hogeContents);
    }

    /**
     *Number of rows in the list
     */
    @Override
    public int getItemCount() {
        return rowDataList.size();
    }
}

4. Generate RecylerView with Activity

Create a RecyclerView with Activity. Once generated, set the Adapter.

public class MainActivity extends AppCompatActivity {

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

        RecyclerView recyclerView = findViewById(R.id.main_recycler_view);

        //Turn on the setting that does not change the layout size of RecyclerView
        //Settings for improving performance.
        recyclerView.setHasFixedSize(true);

        //Set layoutManager in RecyclerView.
        //Depending on the type of this layoutManager, you can select "one-column list" or "two-column list".
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        //Generate Adapter and set it in RecyclerView
        RecyclerView.Adapter mainAdapter = new MainAdapter(createRowData());
        recyclerView.setAdapter(mainAdapter);
    }

    private List<RowData> createRowData() {
        List<RowData> dataSet = new ArrayList<>();
        int i = 0;
        while (i < 20) {
            RowData data = new RowData();

            data.hogeTitle = "HogeTitle!!";
            data.hogeContents = "HogeHogeHogeHogeHogeHogeHogeHogeHogeHogeHoge";

            dataSet.add(data);
            i = i + 1;
        }
        return dataSet;
    }

    class RowData {
        Image hogeImage;
        String hogeTitle;
        String hogeContents;
    }
}

I will build it when I can do it so far. Screenshot_1588515747.png

It's done.

reference

Recommended Posts

[For beginners] Minimum sample to display RecyclerView in Java
[For beginners] Minimum sample to update RecyclerView with DiffUtils in Java
Rock-paper-scissors game for beginners in Java
Display Firestore data in RecyclerView [Java]
[For beginners] Run Selenium in Java
Sample to unzip gz file in Java
[For beginners] How to debug in Eclipse
[Java] [For beginners] How to insert elements directly in a 2D array
How to display a web page in Java
Set pop-up display for Java language in vim.
[Introduction to Java] Basics of java arithmetic (for beginners)
Things to watch out for in Java equals
Sample code to convert List to List <String> in Java Stream
[For beginners] How to operate Stream API after Java 8
Java development for beginners to start from 1-Vol.1-eclipse setup
Introduction to Java for beginners Basic knowledge of Java language ①
How to execute WebCamCapture sample of NyARToolkit for Java
Java debug execution [for Java beginners]
[Java] Basic statement for beginners
[Java] How to display Wingdings
Java for beginners, data hiding
Java application for beginners: stream
[For beginners] Explanation of classes, instances, and statics in Java
Difficult to handle minimum values for Java8 LocalDateTime and Java6 Date
For Java beginners: List, Map, Iterator / Array ... How to convert?
[Rails] How to display error messages for comment function (for beginners)
Java code sample to acquire and display DBLINK source and destination data in Oracle Database using DBLINK
[For beginners] Summary of java constructor
Java for beginners, expressions and operators 1
Multithreaded to fit in [Java] template
I tried setting Java beginners to use shortcut keys in eclipse
How to learn JAVA in 7 days
[For super beginners] The minimum knowledge you want to keep in mind with hashes and symbols
Java for beginners, expressions and operators 2
Log output to file in Java
A simple sample callback in Java
Source to display character array with numberPicker in Android studio (Java)
How to use classes in Java?
How to name variables in Java
Sample code to call the Yahoo! Local Search API in Java
Try to implement Yubaba in Java
Settings for SSL debugging in Java
Sample to read and write LibreOffice Calc fods file in Java 2021
Java, arrays to start with beginners
[For Java beginners] About exception handling
Sample vending machine made in Java
Classes and instances Java for beginners
How to concatenate strings in java
How to display characters entered in Spring Boot on a browser and reference links [Introduction to Spring Boot / For beginners]
Sample code to get key JDBC type values in Java + H2 Database
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Practice of Java programming basics-I want to display triangles with for statements ①
I wrote EX25 of AtCoder Programming Guide for beginners (APG4b) in java.
Minimum configuration sample to automatically release Lambda by Java with Code pipeline
Practice of Java programming basics-I want to display triangles with for statements ②
(For super beginners) Getter / setter and property to think in D language
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
Try to solve Project Euler in Java
Easy to make Slack Bot in Java