Android中RecyclerView項滾動時的動畫
在深入探討RecyclerView項動畫示例之前,我們應該瞭解Android中的RecyclerView是什麼。RecyclerView是ListView的更高階版本,它基於ViewHolder設計模式工作。使用RecyclerView,我們可以顯示網格和專案列表。
CardView由FrameLayout擴充套件,用於以卡片方式顯示專案。它支援半徑和陰影作為預定義標籤。
此示例演示如何透過建立一個顯示學生姓名和年齡的漂亮學生記錄應用程式,將動畫整合到帶有CardView的RecyclerView中。
步驟1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟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 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding="utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" xmlns:app =" http://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>
在上面的程式碼中,我們將RecyclerView新增到視窗管理器作為相對父佈局。
步驟4 - 將以下程式碼新增到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。在studentAdapter中,我們傳遞了studentDatalist作為ArrayList。StudentDatalist包含學生的姓名和年齡。
為了比較RecyclerView項,我們使用了集合框架和sort方法,如下所示:
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});在上面的程式碼中,我們使用名稱來比較元素。
步驟5 - 以下是修改後的檔案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);
}
}
}在介面卡類中,我們有四個方法,如下所示:
onCreateViewHolder():- 用於建立一個ViewHolder,並返回一個檢視。
onBindViewHolder() - 它將與建立的ViewHolder繫結。
getItemCount() - 它包含列表的大小。
MyViewHolder類- 這是一個ViewHolder內部類,它由RecyclerView.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()方法,在這個方法中,我們傳遞了子項的父項及其位置,如下所示:
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;
}
}在上述方法中,我們使用大於(>)號將當前位置與最後位置進行比較,然後我們從AnimationUtils類應用動畫。
步驟6 - 以下是修改後的xml檔案res/layout/student_list_row.xml的內容。
<?xml version = "1.0" encoding = "utf-8"?> <android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:card_view = "http://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內為姓名和年齡建立了兩個TextView。CardView包含預定義的圓角和陰影屬性。因此,我們使用了CardView的圓角。
步驟7 - 以下是修改後的檔案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;
}
}上面的程式碼介紹了studentData物件。讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您專案中的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

現在向下滾動到RecyclerView,它將顯示如下結果:

現在檢視最後一個元素,它正在載入動畫。如下所示,還有更多參考示例:
點選這裡下載專案程式碼
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP