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

【Android開発】RecyclerViewとCardViewを組み合わせた学生リストアプリの作り方

はじめに

RecyclerView(リサイクラービュー)とCardView(カードビュー)を使った実装例を見ていく前に、まずはそれぞれの基本について確認しておきましょう。

RecyclerViewは、従来のListViewをより高度に進化させたUIコンポーネントです。ViewHolderデザインパターンに基づいて動作し、大量のデータを効率的に表示できるのが特徴です。グリッド形式やリスト形式など、さまざまなレイアウトで項目一覧を表示できます。

一方、CardViewはFrameLayoutを継承したコンポーネントで、項目をカード状に美しく表示するために使われます。角丸(radius)や影(shadow)があらかじめ定義された属性として用意されており、簡単にモダンなデザインを実現できます。

本記事では、これら2つのコンポーネントを連携させる方法を、学生の「名前」と「年齢」をカード形式で表示するサンプルアプリを作りながら解説します。


ステップ1:新規プロジェクトの作成

Android Studioで新しいプロジェクトを作成します。メニューからFile ⇒ New Projectを選択し、必要事項を入力してプロジェクトを作成しましょう。

ステップ2:ライブラリ依存関係の追加

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

ステップ3:メインレイアウトの編集

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.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 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 GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(manager);
        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)を渡しています。

グリッド表示を実現するには、以下のようにGridLayoutManagerを使用します。

RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);

ここではLayoutManagerとしてGridLayoutManagerを指定し、列数を2に設定しています。これにより、1行に2つのグリッドが並んで表示されます。

また、RecyclerViewの項目を名前順にソートするために、Collectionsクラスのsortメソッドを使用しています。

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

上記のコードでは、要素を名前(name)で比較して並べ替えています。

ステップ5:StudentAdapter.javaの作成

次に、src/StudentAdapter.javaを以下のように作成します。

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 {
    List studentDataList;
    public StudentAdapter(List 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を生成し、Viewを返すメソッドです。
  • onBindViewHolder():生成されたViewHolderにデータをバインド(紐付け)します。
  • getItemCount():リストのサイズを返します。
  • MyViewHolderクラス:RecyclerView.ViewHolderを継承したインナークラスで、各項目のViewへの参照を保持します。

各カードの背景色をランダムに設定するため、AndroidのRandomクラスを使ってランダムな色を生成し、項目の親レイアウトに適用しています。

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

ステップ6:リスト項目レイアウトの作成

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属性で角丸の半径を設定するだけで、おしゃれなカードデザインになります。

ステップ7:データクラスの作成

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

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

これは、学生の名前と年齢を保持するシンプルなデータオブジェクトです。

アプリの実行

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

【Android開発】RecyclerViewとCardViewを組み合わせた学生リストアプリの作り方

さらに下にスクロールすると、RecyclerViewの残りの項目も以下のように表示されます。

【Android開発】RecyclerViewとCardViewを組み合わせた学生リストアプリの作り方

  1. コントローラー対応で快適に遊べるiOS・Androidおすすめゲーム21選

    数年前、AppleがiOSデバイス向けに公式のゲームコントローラー対応を導入したことは、大きな転換点となりました。タッチ操作でも十分楽しめるとはいえ、コントローラー対応はプレイ体験をまったく新しいレベルへと引き上げてくれます。もちろんAndroidでは、コントローラー対応は以前から実現していました。 この記事では、コントローラーを使うことで真価を発揮するゲーム、あるいはコントローラーなしでは正直プレイが難しいタイトルに絞ってご紹介します。パズルゲームやポイント&クリック型アドベンチャーなどは対象外です。始める前に、お使いのiOSまたはAndroidデバイスにゲームコントローラーを接続しておき

  2. AndroidでSIMカードが認識されない・使えない問題を解決する11の方法

    新しいSIMカードを購入した、あるいは古いSIMカードをAndroidスマートフォンに挿してインターネットに接続しようとしたところ、「SIMカードが検出されません」というエラーが表示されて困っていませんか?SIMカードを何度も抜き差しして正しく挿入されているか確認しても、同じエラーが出続けると途方に暮れてしまうものです。この記事では、SIMスロットが機能しない問題の原因と、効果的な解決策を順番に詳しく解説します。 AndroidでSIMカードが機能しない主な原因 機内モードがオンになっている 対応していないネットワークモードが設定されている SIMカードが無効化されている ネットワークのA