Android 中 Card View 和 Recycler View 的结合使用
在了解 Recycler View 示例中的 Card View 之前,我们应该了解 Android 中的 Recycler View 是什么。Recycler View 是列表视图的更高级版本,它基于 View Holder 设计模式。使用 Recycler View,我们可以显示网格和项目列表。
Card View 扩展了框架布局,用于以卡片方式显示项目。它支持半径和阴影作为预定义标签。
本示例演示了如何将 Recycler View 与 Card View 集成,创建一个美观的学生记录应用,显示学生姓名和年龄。
步骤 1 − 在 Android Studio 中创建一个新项目,转到"文件"->"新建项目",并填写所有必需的详细信息以创建新项目。
步骤 2 − 打开 build.gradle 并添加 Recycler View 和 Card View 库依赖项。
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>
在上面的代码中,我们将 Recycler 视图作为相对父布局添加到窗口管理器中。
步骤 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 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);
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
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);
}
});
}
}
在上面的代码中,我们添加了 Recycler 视图和 StudentAdapter。在 Student Adapter 中,我们将 StudentDatalist 作为数组列表传递。Student 数据列表包含学生姓名和年龄。
要获取网格,我们必须使用如下所示的网格布局管理器 -
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
在上面的代码中,我们使用了 Gridlayout Manager 作为布局管理器,并添加了 2 个单元格。因此,结果将显示每行两个网格。
为了比较 Recycler View 中的项目,我们使用了集合框架和排序方法,如下所示 -
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.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 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():- 用于创建视图持有者并返回一个视图。
onBindViewHolder() - 它将与创建的视图持有者绑定。
getItemCount() - 它包含列表的大小。
MyViewHolder 类 - 它是视图持有者的内部类,由 RecyclerView.ViewHolder 扩展
为了给 Recycler 视图项设置随机背景,我们使用 random 类(Android 中的预定义类)生成了随机颜色,并将颜色添加到视图项的父级,如下所示 -
Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor);
步骤 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>
在上面的列表项视图中,我们在卡片视图中创建了两个文本视图,分别用于姓名和年龄。卡片视图包含预定义的圆角半径和阴影属性。因此,我们在卡片视图中使用了圆角半径。
步骤 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;
}
}
以上代码提供了学生数据对象的信息。让我们尝试运行您的应用程序。假设您已将实际的 Android 移动设备连接到电脑。要从 Android Studio 运行该应用程序,请打开项目的某个活动文件,然后点击工具栏上的"运行"图标
。选择您的移动设备作为选项,然后勾选将显示默认屏幕 −

现在向下滚动到 recyclerview,它将显示如下所示的结果 -

点击此处下载项目代码

