【Android】RecyclerViewのアイテムをスクロール時にアニメーション表示させる方法
RecyclerViewのアニメーションとは
RecyclerViewのItemアニメーションの実装例を紹介する前に、まずAndroidにおけるRecyclerViewについて簡単におさらいしておきましょう。RecyclerViewはListViewの進化版にあたるウィジェットで、ViewHolderデザインパターンに基づいて動作します。RecyclerViewを使うことで、グリッド形式やリスト形式のアイテムを効率よく表示できます。
CardViewはFrameLayoutを拡張したウィジェットで、アイテムをカード状に見せたい場合に使用します。角丸(radius)や影(shadow)があらかじめ定義された属性として用意されているのが特徴です。
本記事では、CardViewと組み合わせてRecyclerViewにアニメーションを統合する方法を、「生徒の名前と年齢を表示する美しい学生記録アプリ」を作成しながら解説します。リストをスクロールすると、新しいアイテムがスライドインのアニメーションとともに表示される仕組みです。
実装手順
ステップ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:レイアウトファイル(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 android.widget.LinearLayout;
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,MainActivity.this);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
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を設定し、アダプターにはstudentDataList(ArrayList)を渡しています。学生データのリストには、名前と年齢が含まれています。
RecyclerViewのアイテムを比較・並べ替えるために、Collectionsフレームワークのsortメソッドを使用しています。
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});上記のコードでは、要素同士を「名前」で比較してソートしています。
ステップ5:StudentAdapter.javaの作成
src/StudentAdapter.java の内容は以下の通りです。
package com.example.andy.tutorialspoint;
import android.content.Context;
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.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
class StudentAdapter extends RecyclerView.Adapter {
List studentDataList;
Context context;
private int lastPosition = -1;
public StudentAdapter(List studentDataList, Context context) {
this.studentDataList=studentDataList;
this.context=context;
}
@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));
setAnimation(viewHolder.parent, i);
}
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@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を生成し、ビューを返します。
- onBindViewHolder():生成されたViewHolderにデータをバインドします。
- getItemCount():リストのサイズを返します。
- MyViewHolderクラス:RecyclerView.ViewHolderを継承したインナークラス(ViewHolder)です。
RecyclerViewの各アイテムにランダムな背景色を設定するため、Randomクラス(Androidにあらかじめ用意されているクラス)を使ってランダムな色を生成し、アイテムビューの親要素に色を適用しています。
Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor);
アニメーションの設定にはsetAnimation()メソッドを使用し、引数として子アイテムの親ビューと位置(position)を渡します。
setAnimation(viewHolder.parent, i);
ここでviewHolder.parentは子アイテムレイアウト内のLinearLayout、"i"はそのビューの位置を表します。
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}このメソッドでは、現在の位置(position)と最後に表示した位置(lastPosition)を比較演算子「>」で判定し、初めて画面に表示されるアイテムに対してのみ、AnimationUtilsクラスから読み込んだアニメーション(android.R.anim.slide_in_left:左からのスライドイン)を適用しています。
ステップ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には角丸と影のプロパティがあらかじめ定義されているため、ここではcardCornerRadius(角丸)を利用しています。
ステップ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(実行)アイコンをクリックします。接続したモバイルデバイスを選択すると、端末にデフォルトの画面が表示されます。

次にRecyclerViewを下へスクロールすると、以下のように表示されます。

最後の要素に注目してください。新しいアイテムがアニメーション付きで読み込まれていることがわかります。このように、lastPositionとの比較によって初回表示時のみアニメーションを適用することで、スクロールのたびに自然な演出を実現できます。
-
【Android】RecyclerViewのアイテムが画面に表示される際にアニメーションを付ける方法
はじめに このチュートリアルでは、AndroidアプリのRecyclerViewにアイテムが表示されるタイミングでアニメーションを適用する方法を、サンプルコードとともに詳しく解説します。 レイアウトアニメーション(Layout Animation)を活用すれば、リストの各アイテムが順番にフェードイン・スライドインする演出を簡単に実現できます。本記事では、FAB(フローティングアクションボタン)をタップするたびに4種類のアニメーションが切り替わるデモアプリを作成します。 手順1:新規プロジェクトの作成 Android Studioを起動し、File → New Projectを選択します。必要
-
Androidアプリで様々な画面サイズに対応する方法!DisplayMetricsで画面サイズ(dp)を取得する手順を解説
Android端末はスマートフォンからタブレットまで、画面サイズや解像度が実に様々です。本記事では、DisplayMetricsクラスを使って端末の画面サイズをdp単位で取得・表示するサンプルアプリを通じて、Androidで様々な画面サイズに対応するための基本を解説します。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトのセットアップを完了させてください。 ステップ2:レイアウトファイル(activity_main.xml)の編集 次に、r