【Android開発】RecyclerViewを使って横スクロールできる水平リスト(HorizontalListView)を作成する方法
はじめに
この記事では、Androidアプリで横スクロール可能なリストビュー(水平方向のListView)をRecyclerViewを使って実装する方法を、ステップごとにわかりやすく解説します。標準のListViewは縦スクロールが基本のため、横方向に並べたい場合はRecyclerViewのLinearLayoutManagerを活用するのが定番の手法です。
手順1:プロジェクトの作成と依存関係の追加
まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。
次に、build.gradle(appレベル)に以下の依存関係を追加します。
implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0'
ポイント: RecyclerViewでリスト表示を構築し、CardViewでアイテムにカード型のデザインを適用します。追加後は「Sync Now」をクリックして同期を忘れないようにしましょう。
手順2:メインレイアウトの編集
res/layout/activity_main.xml に以下のコードを記述します。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="6dp"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>画面中央にRecyclerViewを配置するシンプルな構成です。
手順3:MainActivity.java の実装
src/MainActivity.java に以下のコードを追加します。
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
ArrayList<String> numberName;
ArrayList<Integer> numberImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberName = new ArrayList<>(Arrays.asList("Four...", "Nine... ", "Seven...", "Six...", "Ten...", "Three...", "Two..."));
numberImage = new ArrayList<>(Arrays.asList(R.drawable.four, R.drawable.nine, R.drawable.seven,
R.drawable.six, R.drawable.ten, R.drawable.three, R.drawable.two));
// Calling the RecyclerView
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
// The number of Columns
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(MainActivity.this, numberName, numberImage);
recyclerView.setAdapter(adapter);
}
}重要なポイントは以下の行です。
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
第二引数に LinearLayoutManager.HORIZONTAL を指定することで、通常は縦に並ぶRecyclerViewが横方向にスクロールするリストになります。
手順4:アダプタークラス(MyAdapter.java)の作成
新しいJavaクラス「MyAdapter.java」を作成し、以下のコードを記述します。
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.recyclerview.widget.RecyclerView;
class MyAdapter extends RecyclerView.Adapter <MyAdapter.ViewHolder>{
private ArrayList<String>numberName;
private ArrayList<Integer> numberImage;
private Context context;
MyAdapter(Context context, ArrayList<String> numberName, ArrayList<Integer> numberImage) {
super();
this.context = context;
this.numberName = numberName;
this.numberImage = numberImage;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.gridlayout, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.textView.setText(numberName.get(i));
viewHolder.imgThumbnail.setImageResource(numberImage.get(i));
viewHolder.setClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
if (isLongClick) {
Toast.makeText(context, "#" + position + " - " + numberName.get(position) + " (Long
click)", Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context, MainActivity.class));
} else {
Toast.makeText(context, "#" + position + " - " + numberName.get(position),
Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public int getItemCount() {
return numberName.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnLongClickListener {
ImageView imgThumbnail;
TextView textView;
private ItemClickListener clickListener;
ViewHolder(View itemView) {
super(itemView);
imgThumbnail = itemView.findViewById(R.id.imgThumbnail);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
@Override
public void onClick(View view) {
clickListener.onClick(view, getPosition(), false);
}
@Override
public boolean onLongClick(View view) {
clickListener.onClick(view, getPosition(), true);
return true;
}
}
}
このアダプターでは、各アイテムに対してクリック時と長押し時の両方のイベント処理を実装しています。タップするとアイテム名をToastで表示し、長押しすると別のActivityへ遷移するサンプルです。
手順5:リストアイテム用レイアウトの作成
res/layout 配下に新しいレイアウトリソースファイル(gridlayout.xml)を作成し、以下のコードを記述します。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:card_view="https://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="9dp"
card_view:cardCornerRadius="3dp"
card_view:cardElevation="0.01dp">
<RelativeLayout
android:id="@+id/topLayout"
android:layout_width="match_parent"
android:layout_height="160dp">
<ImageView
android:id="@+id/imgThumbnail"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_above="@+id/textView"
android:layout_centerHorizontal="true"
android:scaleType="fitXY" />
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_gravity="bottom"
anroid:background="#ff444444"
android:gravity="center_vertical"
android:paddingStart="5dp"
android:paddingEnd="2dp"
android:text="Test"
android:textColor="#fff"
android:textSize="20sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
CardViewの中に画像(ImageView)とラベル(TextView)を縦に配置した、カード型のアイテムレイアウトです。
手順6:インターフェース(ItemClickListener.java)の作成
クリックイベントを受け取るためのインターフェースを作成します。新しいJavaクラスとして ItemClickListener.java を追加し、以下のコードを記述してください。
import android.view.View;
interface ItemClickListener {
void onClick(View view, int position, boolean isLongClick);
}手順7:AndroidManifest.xml の確認
最後に、androidManifest.xml にMainActivityが正しく登録されていることを確認します。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>アプリの実行と動作確認
それでは、実際にアプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを前提とします。Android Studioからアプリを起動するには、プロジェクト内のいずれかのActivityファイルを開き、ツールバーの実行(Run)アイコンをクリックします。表示される選択肢から自分のモバイルデバイスを選択すると、端末にデフォルト画面が表示されます。

まとめ
今回は、RecyclerViewのLinearLayoutManagerをHORIZONTALモードに設定することで、横スクロール対応のリストビューを簡単に実装する方法をご紹介しました。画像ギャラリー、商品一覧、カテゴリ選択など、横並びのUIが必要な場面で幅広く応用できます。ぜひ自身のプロジェクトでも試してみてください。
-
【Android】角丸のListViewを作成する方法をステップごとに解説
このチュートリアルでは、Androidアプリで角丸(ラウンドコーナー)のListViewを作成する方法を、サンプルコードとともにステップごとに解説します。カスタムdrawableリソースを利用することで、ListViewの背景に角丸デザイン・グラデーション・枠線を簡単に適用できます。 ステップ1 − 新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。 ステップ2 − レイアウトファイルへコードを追加 res/layout/activ
-
【Android】ExpandableListViewでマルチレベル(階層型)リストを作成する方法
Androidアプリ開発では、カテゴリごとに項目を整理したマルチレベル(階層型)リストを実装したいケースが多くあります。本記事では、ExpandableListViewを使用して、親項目(グループ)をタップすると子項目が展開される2階層リストを作成する方法を、サンプルコードとともにステップごとに解説します。 ExpandableListViewとは? ExpandableListViewは、親項目(グループ)と子項目からなる2階層構造のリストを表示できるAndroid標準ウィジェットです。設定画面やFAQなど、階層的なデータをわかりやすく見せたい場面で活用できます。今回はスポーツ選手の一覧を例