AndroidでRecyclerViewを使って横方向リストビューを実装する方法を徹底解説
はじめに:RecyclerViewとは
具体的な実装例に入る前に、まずAndroidにおけるRecyclerViewについて簡単におさらいしておきましょう。RecyclerViewはListViewのより高度なバージョンであり、ViewHolderデザインパターンに基づいて動作します。RecyclerViewを利用することで、グリッド形式やリスト形式のアイテムを効率的に表示できます。
本記事では、学生の名前と年齢を表示するスタイリッシュな「学生記録アプリ」を作成しながら、RecyclerViewで横方向(水平)にスクロールするリストビューを構築する方法を段階的に解説していきます。
ステップ1:新規プロジェクトの作成
Android Studioを起動し、File → New Project を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。
ステップ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'
}ステップ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 = "horizontal" />
</RelativeLayout>上記コードでは、親レイアウトとしてRelativeLayoutの中にRecyclerViewを配置し、android:scrollbars = "horizontal" を指定することで横方向へのスクロールを有効にしています。
ステップ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);
recyclerView = findViewById(R.id.recycler_view);
studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
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 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をセットアップしています。アダプターには学生データのArrayList(studentDataList)を渡しており、このリストには学生の名前と年齢が格納されています。
横スクロールを実現するポイント
横方向のビューを表示するには、LayoutManagerを以下のように設定することが重要です。
RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(manager);
LinearLayoutManagerの第2引数に LinearLayoutManager.HORIZONTAL を指定することで、RecyclerViewが横方向にスクロールするようになります。これが水平リストビュー実装の核心部分です。
ステップ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 {
List<studentData> 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);
}
}
}アダプタークラスの主要メソッド
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);
ステップ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には角丸(corner radius)や影(shadow)といったプロパティがあらかじめ用意されているため、ここでは角丸を活用して見た目を整えています。
ステップ7:studentData.javaの作成
src/studentData.java の内容は以下の通りです。
class studentData {
String name;
int age;
public studentData(String name, int age) {
this.name = name;
this.age = age;
}
}上記コードは、学生の名前と年齢を保持するデータオブジェクト(モデルクラス)を定義したものです。
アプリの実行と動作確認
それでは、アプリケーションを実行してみましょう。実際のAndroid端末をパソコンに接続していることを前提とします。Android Studioからアプリを起動するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。接続したモバイルデバイスを選択すると、端末にデフォルト画面が表示されます。

続けてRecyclerViewを横方向にスワイプ・スクロールすると、以下のようにカード型のアイテムが左右に流れるように表示され、それぞれ異なる背景色で学生の名前と年齢が確認できます。

-
【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:プロジ