【Android】GridLayoutManagerとRecyclerViewで作るシンプルなグリッド表示の実装例
RecyclerViewとは?
GridLayoutManagerを使ったRecyclerViewのグリッド表示の例に入る前に、まずAndroidにおけるRecyclerViewとは何かをおさらいしておきましょう。RecyclerViewはListViewをさらに進化させた高度なコンポーネントで、ViewHolderデザインパターンに基づいて動作します。RecyclerViewを利用することで、グリッド形式やリスト形式のアイテムをメモリ効率よく表示できます。
本記事で作成するアプリ
この記事では、学生の名前と年齢をグリッド状に表示する「学生記録アプリ」を題材に、RecyclerViewとGridLayoutManagerを組み合わせる方法を段階的に解説します。
手順1:新規プロジェクトを作成する
Android StudioでFile → New Projectを選択し、必要事項をすべて入力して新しいプロジェクトを作成します。
手順2:build.gradleに依存関係を追加する
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を編集する
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 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.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をセットアップし、アダプターには学生の名前と年齢を格納したArrayList(studentDataList)を渡しています。
グリッド表示を実現するには、次のようにGridLayoutManagerを使用します。
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
ここではレイアウトマネージャーとして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の内容は以下のとおりです。
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を生成し、Viewを返します。
- 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);
手順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を作成しています。
手順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を連携させる方法を実装例つきで解説
この記事では、AndroidアプリでRecyclerViewとデータベース(SQLite)を連携させて使用する方法を、実際のサンプルコードとともに解説します。連絡先の登録・表示・編集・削除ができるシンプルなアプリを題材に、実装手順をステップごとに見ていきましょう。ステップ1:プロジェクトの作成と依存関係の追加まず、Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、必要事項を入力してプロジェクトを作成してください。続いて、build.gradle(Module: app)に以下の依存関係を追加します。implementat
-
【Android】RecyclerViewで無限スクロール(無限リスト)を実装する方法を徹底解説
はじめに 本記事では、AndroidアプリでRecyclerViewを使って無限リスト(エンドレススクロール)を実装する方法を、サンプルコード付きでステップごとに解説します。リストの最下部までスクロールすると自動的に次のデータが読み込まれるこの仕組みは、SNSやニュース系アプリなどで広く採用されている定番のUIパターンです。 今回実装する主な要素は以下のとおりです。 スクロール位置の検出による追加データ読み込みのトリガー処理 読み込み中に表示するプログレスバー(LoadingViewHolder) 複数のViewTypeを持つRecyclerView.Adapterの実装 手順1:プロジ