如何在Android中更新RecyclerView适配器数据?
在进入示例之前,我们应该了解Android中的RecyclerView是什么。RecyclerView是ListView的更高级版本,它基于ViewHolder设计模式工作。使用RecyclerView,我们可以显示网格和项目列表。
此示例演示了如何通过创建一个漂亮的学生记录应用程序来更新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:layout_marginBottom = "50dp" android:scrollbars = "vertical" /> <LinearLayout android:layout_width = "match_parent" android:layout_below = "@+id/recycler_view" android:layout_marginTop = "-50dp" android:layout_alignParentBottom = "true" android:layout_height = "wrap_content"> <Button android:id = "@+id/add" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "add item"/> <Button android:id = "@+id/remove" android:layout_width = "wrap_content" android:text = "remove item" android:layout_height = "wrap_content" /> </LinearLayout> </RelativeLayout>
在上面的代码中,我们将RecyclerView添加到窗口管理器作为相对父布局,并添加了两个按钮:添加和删除。添加按钮将数据添加到RecyclerView适配器,删除按钮将数据从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.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; 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 studentDataList = new ArrayList<>(); @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button add = findViewById(R.id.add); Button remove = findViewById(R.id.remove); 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(); remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(studentDataList.size()>0) { studentDataList.remove(studentDataList.size() - 1); studentAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show(); } } }); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(studentDataList.size()> = 0) { studentData data = new studentData("raghu ram", 25); studentDataList.add(studentDataList.size(), data); studentAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show(); } } }); } @RequiresApi(api = Build.VERSION_CODES.N) private void StudentDataPrepare() { studentData data = new studentData("sai", 25); studentDataList.add(data); data = new studentData("sai raj", 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包含学生姓名和年龄。我们添加了两个按钮:添加和删除。使用添加按钮,我们可以向ArrayList添加项目,如下所示:
if(studentDataList.size()> = 0) { studentData data = new studentData("raghu ram", 25); studentDataList.add(studentDataList.size(), data); studentAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show(); }
在上面的代码中,我们检查验证,如果ArrayList大小等于零或大于零,则我们将数据添加到ArrayList,并使用了一个特殊的方法notifyDataSetChanged()。此方法指示适配器数据集已修改,因此适配器将在内部刷新视图。
要从ArrayList中删除数据,我们使用了remove()方法,如下所示:
if(studentDataList.size()>0) { studentDataList.remove(studentDataList.size() - 1); studentAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show(); }
在上面的代码中,我们基于size-1删除数据,这意味着它将从底部删除数据。删除数据后,我们使用notifyDataSetChanged()更新适配器。
步骤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<StudentAdapter.MyViewHolder> { List<studentData> studentDataList; public StudentAdapter(List<studentData> 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():用于创建一个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);
步骤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; } }
上面的代码介绍了学生数据对象。让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要在Android Studio中运行应用程序,请打开您的一个项目活动文件,然后单击工具栏中的运行 图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕:
最初元素的结尾是sai raj,年龄为25岁,现在添加两个元素,如下所示:
现在删除所有元素,输出应如下所示:
点击这里下载项目代码