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

【Android】RecyclerViewのアイテムにランダムな背景色を設定する方法を徹底解説

RecyclerViewとは?

RecyclerViewは、AndroidにおけるListViewの進化版であり、ViewHolderデザインパターンに基づいて動作する高度なUIコンポーネントです。RecyclerViewを活用することで、グリッド形式やリスト形式のアイテムを効率的に表示できます。

本記事では、「生徒の名前と年齢を表示する美しい生徒名簿アプリ」を作成しながら、RecyclerViewの各アイテムにランダムな背景色を設定する方法を段階的に解説します。

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

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な情報をすべて入力してプロジェクトを作成しましょう。

手順2:build.gradleにRecyclerViewライブラリを追加

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

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: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'
}

手順3:activity_main.xmlにRecyclerViewを配置

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:scrollbars="vertical" />
</RelativeLayout>

上記のコードでは、親レイアウトとしてRelativeLayoutを使用し、その中にRecyclerViewをウィンドウマネージャーとして追加しています。

手順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.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
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<studentData> studentDataList =new ArrayList<>();
    @TargetApi(Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        studentAdapter=new StudentAdapter(studentDataList);
        RecyclerView.LayoutManager manager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(studentAdapter);
        StudentDataPrepare();
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void StudentDataPrepare() {
        studentData data=new studentData("sai",25);
        studentDataList.add(data);
        data=new studentData("sai",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)を渡しています。

また、RecyclerViewのアイテムを比較・並べ替えるために、Collectionsフレームワークのsortメソッドを以下のように使用しています。

Collections.sort(studentDataList, new Comparator<studentData>() {
    @Override
    public int compare(studentData o1, studentData o2) {
        return o1.name.compareTo(o2.name);
    }
});

このコードでは、生徒の名前を基準に要素を比較しています。

手順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);

ここでは、Color.argb()の第1引数に不透明度255(完全に不透明)を指定し、赤・緑・青の各成分に0〜255のランダムな値を渡すことで、毎回異なる色を生成しています。

手順6:student_list_row.xmlの作成

res/layout/student_list_row.xmlを以下の内容で作成します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:weightSum="1"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:gravity="center"
        android:textSize="15sp"
        android:layout_height="100dp" />
    <TextView
        android:id="@+id/age"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:gravity="center"
        android:textSize="15sp"
        android:layout_height="100dp" />
</LinearLayout>

上記のリストアイテムのビューでは、名前と年齢を表示するための2つのTextViewを作成しています。それぞれ画面幅の50%ずつを占めるようにweightを設定しています。

手順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のアイテムにランダムな背景色を設定する方法を徹底解説

上記の結果では、アルファベット順(Aから)にソートされた生徒データが、ランダムな背景色とともに表示されています。さらに下へスクロールすると、以下のように表示されます。

【Android】RecyclerViewのアイテムにランダムな背景色を設定する方法を徹底解説

まとめ

本記事では、RecyclerViewの各アイテムにランダムな背景色を設定する方法を学びました。ポイントは、onBindViewHolder()内でRandomクラスとColor.argb()を組み合わせて色を生成し、setBackgroundColor()で適用することです。この手法を応用すれば、チャットアプリやSNSのタイムラインなど、視覚的に魅力的なリストUIを簡単に実装できます。

  1. AndroidでAsyncTaskにタイムアウトを設定する方法【サンプルコード付きで解説】

    はじめに このチュートリアルでは、AndroidアプリでAsyncTaskにタイムアウトを設定する方法を、実際に動作するサンプルコードとともに解説します。EditTextに入力した秒数だけバックグラウンド処理をスリープさせ、その間の進捗状況をProgressDialogで表示するシンプルなデモアプリを作成していきます。 実装手順 ステップ1:新規プロジェクトを作成する Android Studioを開き、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。 ステップ2:activity_main.xml にレ

  2. Microsoft Wordで背景画像を設定する方法|文書全体・1ページごとの手順を解説

    Microsoft Wordは、デジタル時代において欠かせない基本ツールの一つとなっています。いつもの文字だけの文書に少し変化をつけて、オリジナリティを加えたいと思ったことはありませんか?そんなときにおすすめなのが、Word文書への背景画像の設定です。実は、Microsoft Wordでは画像を背景として設定することが可能です。本記事では、文書全体または特定の1ページに背景画像を設定する方法を詳しく解説します。「Wordで画像を背景として挿入するにはどうすればいいのか」という疑問にもお答えしますので、ぜひ最後までご覧ください。 Microsoft Wordで背景画像を設定する方法 以下では、