Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android開発】RecyclerViewアダプターのデータを動的に更新する方法を解説

RecyclerViewとは?

具体的な実装例に入る前に、まずAndroidにおけるRecyclerViewについて簡単に確認しておきましょう。RecyclerViewはListViewの上位互換にあたるコンポーネントで、ViewHolderデザインパターンに基づいて動作します。RecyclerViewを活用することで、グリッド形式やリスト形式のアイテムを効率的に表示できます。

本記事では、学生の「名前」と「年齢」を一覧表示するサンプルアプリを作成しながら、RecyclerViewアダプターのデータを更新する方法を段階的に解説します。ボタン操作でリストにアイテムを追加・削除し、そのたびに画面がリアルタイムに更新される仕組みを学びましょう。

Step 1:新規プロジェクトの作成

Android Studioを起動し、File → New Projectから新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトをセットアップしてください。

Step 2:build.gradleにライブラリの依存関係を追加

build.gradleファイルを開き、RecyclerViewとCardViewのライブラリ依存関係を追加します。

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.andy.tutorialspoint"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Step 3:activity_main.xmlにレイアウトを定義

次に、res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
    xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:tools = "https://schemas.android.com/tools"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    app:layout_behavior = "@string/appbar_scrolling_view_behavior"
    tools:showIn = "@layout/activity_main"
    tools:context = ".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id = "@+id/recycler_view"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_marginBottom = "50dp"
        android:scrollbars = "vertical" />
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_below = "@+id/recycler_view"
        android:layout_marginTop = "-50dp"
        android:layout_alignParentBottom = "true"
        android:layout_height = "wrap_content">
        <Button
            android:id = "@+id/add"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "add item"/>
        <Button
            android:id = "@+id/remove"
            android:layout_width = "wrap_content"
            android:text = "remove item"
            android:layout_height = "wrap_content" />
    </LinearLayout>
</RelativeLayout>

上記のコードでは、RelativeLayoutを親レイアウトとしてRecyclerViewを配置し、さらに「追加(add)」と「削除(remove)」の2つのボタンを設置しています。「追加」ボタンはRecyclerViewアダプターにデータを追加し、「削除」ボタンはRecyclerViewからデータを取り除きます。

Step 4:MainActivity.javaに処理を実装

続いて、src/MainActivity.javaに以下のコードを追加します。

package com.example.andy.tutorialspoint;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private StudentAdapter studentAdapter;
    private List studentDataList = new ArrayList<>();
    @TargetApi(Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button add = findViewById(R.id.add);
        Button remove = findViewById(R.id.remove);
        recyclerView = findViewById(R.id.recycler_view);
        studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(studentAdapter);
        StudentDataPrepare();
        remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(studentDataList.size()>0) {
                    studentDataList.remove(studentDataList.size() - 1);
                    studentAdapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
                }
            }
        });
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(studentDataList.size()> = 0) {
                    studentData data = new studentData("raghu ram", 25);
                    studentDataList.add(studentDataList.size(), data);
                    studentAdapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void StudentDataPrepare() {
        studentData data = new studentData("sai", 25);
        studentDataList.add(data);
        data = new studentData("sai raj", 25);
        studentDataList.add(data);
        data = new studentData("raghu", 20);
        studentDataList.add(data);
        data = new studentData("raj", 28);
        studentDataList.add(data);
        data = new studentData("amar", 15);
        studentDataList.add(data);
        data = new studentData("bapu", 19);
        studentDataList.add(data);
        data = new studentData("chandra", 52);
        studentDataList.add(data);
        data = new studentData("deraj", 30);
        studentDataList.add(data);
        data = new studentData("eshanth", 28);
        studentDataList.add(data);
        Collections.sort(studentDataList, new Comparator() {
            @Override
            public int compare(studentData o1, studentData o2) {
                return o1.name.compareTo(o2.name);
            }
        });
    }
}

このコードでは、RecyclerViewとStudentAdapterを関連付けています。StudentAdapterには、学生データのリスト(studentDataList)をArrayListとして渡しています。リストには学生の名前と年齢が格納され、「追加」と「削除」の2つのボタンが用意されています。

データを追加する処理

「追加」ボタンを使うと、次のようにArrayListへアイテムを追加できます。

if(studentDataList.size()> = 0) {
    studentData data = new studentData("raghu ram", 25);
    studentDataList.add(studentDataList.size(), data);
    studentAdapter.notifyDataSetChanged();
    Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
}

ここでは、ArrayListのサイズが0以上であるかを検証した上でデータを追加しています。ポイントはnotifyDataSetChanged()というメソッドです。このメソッドを呼び出すことで、アダプターに「データセットが変更された」ことを通知し、アダプター内部で自動的にビューを再描画してくれます。

データを削除する処理

ArrayListからデータを削除するには、remove()メソッドを以下のように使用します。

if(studentDataList.size()>0) {
    studentDataList.remove(studentDataList.size() - 1);
    studentAdapter.notifyDataSetChanged();
    Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
}

上記のコードでは、「サイズ - 1」の位置のデータを削除しています。つまり、リストの末尾からデータを取り除く処理です。削除後も、notifyDataSetChanged()を使ってアダプターに変更を反映させています。

Step 5:StudentAdapter.javaを作成

次に、src/StudentAdapter.javaを以下の内容で作成します。

package com.example.andy.tutorialspoint;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;

class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
    List<studentData> studentDataList;
    public StudentAdapter(List<studentData> studentDataList) {
        this.studentDataList = studentDataList;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
        .inflate(R.layout.student_list_row, viewGroup, false);
        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(MyViewHolder viewHolder, int i) {
        studentData data = studentDataList.get(i);
        Random rnd = new Random();
        int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        viewHolder.parent.setBackgroundColor(currentColor);
        viewHolder.name.setText(data.name);
        viewHolder.age.setText(String.valueOf(data.age));
    }
    @Override
    public int getItemCount() {
        return studentDataList.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView name,age;
        LinearLayout parent;
        public MyViewHolder(View itemView) {
            super(itemView);
            parent = itemView.findViewById(R.id.parent);
            name = itemView.findViewById(R.id.name);
            age = itemView.findViewById(R.id.age);
        }
    }
}

アダプタークラスには、以下の4つの重要な要素が含まれています。

  • onCreateViewHolder():ViewHolderを生成し、ビューを返すメソッドです。
  • onBindViewHolder():生成されたViewHolderにデータをバインド(結び付け)します。
  • getItemCount():リストのサイズを返します。
  • MyViewHolderクラス:RecyclerView.ViewHolderを継承した、ViewHolderのインナークラスです。

また、RecyclerViewの各アイテムにランダムな背景色を設定するため、Androidに組み込まれているRandomクラスを使ってランダムな色を生成し、アイテムビューの親レイアウトに適用しています。

Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);

Step 6:student_list_row.xmlにリスト行のレイアウトを定義

続いて、res/layout/student_list_row.xmlを以下の内容に変更します。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:card_view = "https://schemas.android.com/apk/res-auto"
    android:layout_width = "match_parent"
    card_view:cardCornerRadius = "4dp"
    android:id = "@+id/card_view"
    android:layout_margin = "10dp"
    android:layout_height = "200dp">
    <LinearLayout
        android:id = "@+id/parent"
        android:layout_gravity = "center"
        android:layout_width = "match_parent"
        android:orientation = "vertical"
        android:gravity = "center"
        android:layout_height = "match_parent">
    <TextView
        android:id = "@+id/name"
        android:layout_width = "wrap_content"
        android:gravity = "center"
        android:textSize = "25sp"
        android:textColor = "#FFF"
        android:layout_height = "wrap_content" />
    <TextView
        android:id = "@+id/age"
        android:layout_width = "wrap_content"
        android:gravity = "center"
        android:textSize = "25sp"
        android:textColor = "#FFF"
        android:layout_height = "wrap_content" />
    </LinearLayout>
</android.support.v7.widget.CardView>

このリストアイテムビューでは、CardViewの中に「名前」と「年齢」を表示する2つのTextViewを配置しています。CardViewは角丸(コーナー半径)や影といったプロパティがあらかじめ用意されているため、ここではcardCornerRadiusを活用しています。

Step 7:studentData.javaでデータクラスを定義

最後に、src/studentData.javaを以下の内容で作成します。

package com.example.andy.tutorialspoint;

class studentData {
    String name;
    int age;
    public studentData(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

このコードは、学生データ(名前と年齢)を保持するデータオブジェクトを定義したものです。

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。Android端末をパソコンに接続していることを前提とします。Android Studioからプロジェクトのアクティビティファイルを開き、ツールバーのRunアイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、以下のような初期画面が表示されます。

【Android開発】RecyclerViewアダプターのデータを動的に更新する方法を解説

初期状態では、リストの末尾に「年齢25歳のsai raj」が表示されています。ここで「追加」ボタンを2回押すと、次のようにアイテムが追加されます。

【Android開発】RecyclerViewアダプターのデータを動的に更新する方法を解説

さらに「削除」ボタンですべての要素を取り除くと、出力は次のようになります。

【Android開発】RecyclerViewアダプターのデータを動的に更新する方法を解説

まとめ

このように、RecyclerViewアダプターのデータを更新する際の鍵となるのはnotifyDataSetChanged()メソッドです。データリスト(ArrayList)を直接操作した後にこのメソッドを呼び出すだけで、アダプターが自動的に変更を検知し、画面を再描画してくれます。追加・削除のどちらのケースでも同じ仕組みで対応できるため、ぜひ実際のプロジェクトでも活用してみてください。

  1. Androidでアプリを更新する方法|自動更新と手動更新の設定ガイド

    Androidのアプリは、開発者によって機能改善を目的としたアップデートが定期的に配信されています。アップデートには、動作の安定性やパフォーマンスの向上に加えて、セキュリティ修正が含まれることも少なくありません。デフォルトではAndroidアプリは自動的に更新されるようになっていますが、実は「いつ」「どのように」更新するかをユーザー自身である程度コントロールできることをご存じない方も多いはず。この記事では、Androidでアプリを自動更新する方法と手動更新する方法を詳しく解説します。 Androidでアプリを自動更新する方法 アプリの自動更新を有効にしておけば、新しいバージョンがリリース

  2. Androidのデータバインディング入門:Data Binding Libraryでレイアウトとデータを結びつける方法

    データバインディングとは、アプリが扱う「データ」と、画面上の視覚的なUI要素を結びつける(バインドする)ための手法です。この仕組みを使うと、UI側の値が更新されるたびに、裏側で保持しているデータも自動的に更新されます。 決して目新しい概念ではなく、AngularJS、React、Vueなど、多くのフロントエンドフレームワークがすでにこの仕組みを設計に取り入れています。 しかし本記事で注目するのはフロントエンドフレームワークではなく、モバイル開発です。GoogleはAndroid向けにData Binding Libraryを提供しており、これはAndroid Jetpackの一部として位置づけ