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

Androidで水平リストビューを作成する方法|RecyclerViewを使った横スクロール実装ガイド

Androidアプリ開発では、画像ギャラリー、ニュースフィード、商品一覧など、横方向にスクロールできるリストビュー(水平リスト)が必要になる場面が数多くあります。本記事では、従来のListViewの代わりにRecyclerViewLinearLayoutManagerを組み合わせて、滑らかに動作する水平リストビューを実装する手順を、サンプルコードとともに段階的に解説します。

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

まず、Android Studioを起動し、メニューの「File」→「New Project」から新しいプロジェクトを作成します。プロジェクト名や保存先など、必要事項を入力してセットアップを完了させてください。

ステップ2:メインレイアウト(activity_main.xml)の作成

続いて、res/layout/activity_main.xmlに以下のコードを追加します。ここでは、画面全体を覆う形でRecyclerViewを1つ配置したシンプルな構成にしています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

ステップ3:MainActivity.javaの実装

次に、src/MainActivity.javaに以下のコードを追加します。最重要ポイントは、LinearLayoutManagerの向きをHORIZONTALに設定している箇所です。これを指定するだけで、RecyclerViewが横方向にスクロールするリストへと変わります。

package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private List<MovieModel> movieList = new ArrayList<>();
    private MoviesAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        mAdapter = new MoviesAdapter(movieList);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        prepareMovieData();
    }
    private void prepareMovieData() {
        MovieModel movie = new MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015");
        movieList.add(movie);
        movie = new MovieModel("Inside Out", "Animation, Kids & Family", "2015");
        movieList.add(movie);
        movie = new MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
        movieList.add(movie);
        movie = new MovieModel("Shaun the Sheep", "Animation", "2015");
        movieList.add(movie);
        movie = new MovieModel("The Martian", "Science Fiction & Fantasy", "2015");
        movieList.add(movie);
        movie = new MovieModel("Mission: Impossible Rogue Nation", "Action", "2015");
        movieList.add(movie);
        movie = new MovieModel("Up", "Animation", "2009");
        movieList.add(movie);
        movie = new MovieModel("Star Trek", "Science Fiction", "2009");
        movieList.add(movie);
        movie = new MovieModel("The LEGO Movie", "Animation", "2014");
        movieList.add(movie);
        movie = new MovieModel("Iron Man", "Action & Adventure", "2008");
        movieList.add(movie);
        movie = new MovieModel("Aliens", "Science Fiction", "1986");
        movieList.add(movie);
        movie = new MovieModel("Chicken Run", "Animation", "2000");
        movieList.add(movie);
        movie = new MovieModel("Back to the Future", "Science Fiction", "1985");
        movieList.add(movie);
        movie = new MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981");
        movieList.add(movie);
        movie = new MovieModel("Goldfinger", "Action & Adventure", "1965");
        movieList.add(movie);
        movie = new MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
        movieList.add(movie);
        mAdapter.notifyDataSetChanged();
    }
}

ステップ4:データモデルクラス(MovieModel.java)の作成

リストに表示する映画情報(タイトル・ジャンル・公開年)を保持するためのモデルクラスを作成します。src/MovieModel.javaに以下のコードを追加してください。

package app.com.sample;
public class MovieModel {
    private String title, genre, year;
    public MovieModel() {
    }
    public MovieModel(String title, String genre, String year) {
        this.title = title;
        this.genre = genre;
        this.year = year;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String name) {
        this.title = name;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getGenre() {
        return genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }
}

ステップ5:アイテムレイアウト(movie_list.xml)の作成

リストの各項目(カード)の見た目を定義します。ここではCardViewを使用し、影付きのカード型デザインに仕上げています。res/layout/movie_list.xmlとして以下のコードを追加しましょう。

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="250dp"
    android:layout_height="100dp"
    android:layout_margin="8dp">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp">
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_toStartOf="@+id/year"
            android:textColor="#222222"
            android:textSize="16sp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:textColor="#999999" />
        <TextView
            android:id="@+id/genre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>

ステップ6:アダプタークラス(MoviesAdapter.java)の作成

RecyclerViewへデータを供給するためのアダプターを作成します。ViewHolderパターンを採用し、各位置の映画データをビューにバインドしていきます。src/MoviesAdapter.javaに以下のコードを追加してください。

package app.com.sample;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
    private List<MovieModel> moviesList;
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title, year, genre;
        MyViewHolder(View view) {
            super(view);
            title = view.findViewById(R.id.title);
            genre = view.findViewById(R.id.genre);
            year = view.findViewById(R.id.year);
        }
    }
    public MoviesAdapter(List<MovieModel> moviesList) {
        this.moviesList = moviesList;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.movie_list, parent, false);
        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        MovieModel movie = moviesList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
    }
    @Override
    public int getItemCount() {
        return moviesList.size();
    }
}

ステップ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でプロジェクト内のアクティビティファイルを開き、ツールバーのRun(実行)アイコンAndroidで水平リストビューを作成する方法|RecyclerViewを使った横スクロール実装ガイドをクリックします。表示された候補から接続済みのモバイルデバイスを選択すると、端末上でアプリが起動し、以下のように横方向にスクロールできる映画リストが表示されます。

Androidで水平リストビューを作成する方法|RecyclerViewを使った横スクロール実装ガイド

まとめ

今回のポイントは、LinearLayoutManagersetOrientation(LinearLayoutManager.HORIZONTAL)を指定するだけというシンプルさです。この一行を加えるだけで、縦方向の標準的なリストがカルーセル形式の横スクロールリストに変化します。また、GridLayoutManagerを使えば格子状のグリッド表示に、StaggeredGridLayoutManagerを使えば高さの異なるカードを敷き詰めるマソナリーレイアウトにも対応できるため、用途に応じてLayoutManagerを使い分けるとよいでしょう。

  1. 【Android】ListViewにフッターを追加する方法をステップごとに解説

    このチュートリアルでは、AndroidのListViewにフッター(Footer)を追加する方法を、実際のサンプルコードとともにわかりやすく解説します。リストの末尾に「リストの終わり」などの補足情報を表示したい場合に役立つテクニックです。 ステップ 1:新規プロジェクトを作成する まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 ステップ 2:activity_main.xml にコードを追加する res/layout/activity_main.xml

  2. 【Android開発】ボタンを削除・非表示にする方法をわかりやすく解説

    はじめにこの記事では、Androidアプリでボタンを画面から削除する、または非表示(不可視)にする方法を、実際のサンプルコードとともに解説します。ボタンの表示・非表示を切り替えることは、UIの動的な制御において非常によく使われるテクニックです。Androidでは setVisibility() メソッドを使用することで、ボタンを簡単に非表示にしたり、再表示したりできます。それでは、具体的な手順を見ていきましょう。手順1:新しいプロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成し