6
5

More than 3 years have passed since last update.

[初心者向け]JavaでRecyclerViewを表示するミニマムサンプル

Last updated at Posted at 2020-05-03

はじめに

Androidで再利用可能なViewをリストで表示する際はRecyclerViewというウィジットが主流です。
けど最初は複数のパーツが出てきてよくわからなかったのでミニマムサンプルを作ってみます。

↓完成イメージ
Screenshot_1588515747.png

準備

build.gradleにRecyclerViewを追加します。


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

登場人物

  • Activity
    • RecyclerViewを乗っける土台
  • RecyclerView
    • リストを表示するウィジット
  • ViewHolder
    • リスト一個分のView
  • Adapter
    • RecyclerViewとViewHolderの仲介役。ViewHolder管理していい感じにRecyclerViewにバインドしてくれる。

表示までのステップ

1.RecyclerViewのlayoutファイル作成
2.ViewHolder(リスト一行分)のlayout作成
3.Adapter・ViewHolder作成
4.ActivityでRecylerViewを生成

一個ずつ見ていきましょう。

1.RecyclerViewのlayoutファイル作成

RecyclerViewを表示したいActivityの上にRecyclerViewを乗っけます。(フラグメントを使いたい場合はフラグメントでも同じです。)

スクリーンショット 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.ViewHolder(リスト一行分)のlayout作成

次に一行分のレイアウトを作ります。
今回はこんな感じにします。ここは作りたいリストの内容次第です。

スクリーンショット 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.Adapter・ViewHolder作成

以降順番はあんまり関係ありませんが、今回は最初にAdapterを用意します。
RecyclerViewを生成する際にAdapterのセットが必要になるからです。


public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {

    private List<RowData> rowDataList;

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

    /**
     * 一行分のデータ
     */
    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作るメソッド
     * 最初しか呼ばれない。
     * ここでViewHolderのlayoutファイルをインフレーとして生成したViewHolderを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);
    }

    /**
     * ViewHolderとRecyclerViewをバインドする
     * 一行のViewに対して共通でやりたい処理をここで書く。今回はテキストのセットしかしてないけど。
     */
    @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);
    }

    /**
     * リストの行数
     */
    @Override
    public int getItemCount() {
        return rowDataList.size();
    }
}

4.ActivityでRecylerViewを生成

ActivityでRecyclerViewを生成します。
生成したらAdapterをセットします。
※今回はサンプルなので20行分データを生成して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);

        // RecyclerViewのレイアウトサイズを変更しない設定をONにする
        // パフォーマンス向上のための設定。
        recyclerView.setHasFixedSize(true);

        // RecyclerViewにlayoutManagerをセットする。
        // このlayoutManagerの種類によって「1列のリスト」なのか「2列のリスト」とかが選べる。
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // Adapter生成して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;
    }
}

ここまでできたらビルドしてみます。
Screenshot_1588515747.png

できました。

参考

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5