如何在 Android 中删除多个 RecyclerView 项目?
RecyclerView 是 ListView 的高级版本,具有改进的性能。当您有很长的项目列表要显示时,您可以使用 RecyclerView。它具有重用其视图的能力。在 RecyclerView 中,当视图离开屏幕或对用户不可见时,它不会破坏它,它将重用这些视图。此功能有助于降低功耗并为应用程序提供更高的响应能力。在本文中,我们将看到如何从 android studio 的回收器视图中删除多个项目。在进一步移动之前,让我们了解 RecyclerView。
先决条件:
在实现本文教授的概念之前,您应该具备在 android studio 中实现回收器视图的知识。如果您不知道如何实现回收器视图,请阅读以下文章:Android 中的 RecyclerView 示例
我们将在本文中构建什么?
这是我们将在本文中实现的示例视频。请注意,我们将使用Java语言来实现这个应用程序。
分步实施
第 1 步:创建一个新项目
- 打开一个新项目。
- 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
- 您可以在方便时更改项目的名称。
- 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java
如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?
第 2 步:添加所需的依赖项
打开 Gradle 脚本 > build.gradle(module)。转到应用>右键单击>打开模块设置>依赖项>添加依赖项>库依赖项。
在搜索栏中输入材料,然后单击搜索。选择下图中显示的依赖项-
在搜索栏中输入“lifecycle-extensions”,然后单击搜索。选择下图中显示的依赖项-
第 3 步:在 drawable 中添加新的矢量资源
导航到可绘制 > 右键单击 > 新建 > 矢量资产,然后从剪贴画中选择以下资产。
1.检查圈:
2. 全选:
第 4 步:使用 xml 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。
XML
XML
XML
Java
package com.example.multiple_item_delete;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
// initialize variables
RecyclerView recyclerView;
TextView tvEmpty;
ArrayList arrayList=new ArrayList<>();
MainAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// assign variable
recyclerView=findViewById(R.id.recycler_view);
tvEmpty=findViewById(R.id.tv_empty);
// add values in arraylist
arrayList.addAll(Arrays.asList("One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven"
,"Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen","Twenty"));
// set layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Initialize adapter
adapter=new MainAdapter(this,arrayList,tvEmpty);
// set adapter
recyclerView.setAdapter(adapter);
}
}
Java
package com.example.multiple_item_delete;
import android.app.Activity;
import android.graphics.Color;
import android.text.Layout;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainAdapter extends RecyclerView.Adapter {
// initialize variables
Activity activity;
ArrayList arrayList;
TextView tvEmpty;
MainViewModel mainViewModel;
boolean isEnable=false;
boolean isSelectAll=false;
ArrayList selectList=new ArrayList<>();
// create constructor
public MainAdapter(Activity activity,ArrayList arrayList,TextView tvEmpty)
{
this.activity=activity;
this.arrayList=arrayList;
this.tvEmpty=tvEmpty;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// initialize variables
View view= LayoutInflater.from(parent.getContext()).
inflate(R.layout.item_main,parent,false);
// initialize view Model
mainViewModel= ViewModelProviders.of((FragmentActivity) activity)
.get(MainViewModel.class);
// return view
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// set text on text view
holder.textView.setText(arrayList.get(position));
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// check condition
if (!isEnable)
{
// when action mode is not enable
// initialize action mode
ActionMode.Callback callback=new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// initialize menu inflater
MenuInflater menuInflater= mode.getMenuInflater();
// inflate menu
menuInflater.inflate(R.menu.menu,menu);
// return true
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// when action mode is prepare
// set isEnable true
isEnable=true;
// create method
ClickItem(holder);
// set observer on getText method
mainViewModel.getText().observe((LifecycleOwner) activity
, new Observer() {
@Override
public void onChanged(String s) {
// when text change
// set text on action mode title
mode.setTitle(String.format("%s Selected",s));
}
});
// return true
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// when click on action mode item
// get item id
int id=item.getItemId();
// use switch condition
switch(id)
{
case R.id.menu_delete:
// when click on delete
// use for loop
for(String s:selectList)
{
// remove selected item list
arrayList.remove(s);
}
// check condition
if(arrayList.size()==0)
{
// when array list is empty
// visible text view
tvEmpty.setVisibility(View.VISIBLE);
}
// finish action mode
mode.finish();
break;
case R.id.menu_select_all:
// when click on select all
// check condition
if(selectList.size()==arrayList.size())
{
// when all item selected
// set isselectall false
isSelectAll=false;
// create select array list
selectList.clear();
}
else
{
// when all item unselected
// set isSelectALL true
isSelectAll=true;
// clear select array list
selectList.clear();
// add value in select array list
selectList.addAll(arrayList);
}
// set text on view model
mainViewModel.setText(String .valueOf(selectList.size()));
// notify adapter
notifyDataSetChanged();
break;
}
// return true
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// when action mode is destroy
// set isEnable false
isEnable=false;
// set isSelectAll false
isSelectAll=false;
// clear select array list
selectList.clear();
// notify adapter
notifyDataSetChanged();
}
};
// start action mode
((AppCompatActivity) v.getContext()).startActionMode(callback);
}
else
{
// when action mode is already enable
// call method
ClickItem(holder);
}
// return true
return true;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// check condition
if(isEnable)
{
// when action mode is enable
// call method
ClickItem(holder);
}
else
{
// when action mode is not enable
// display toast
Toast.makeText(activity,"You Clicked"+arrayList.get(holder.getAdapterPosition()),
Toast.LENGTH_SHORT).show();
}
}
});
// check condition
if(isSelectAll)
{
// when value selected
// visible all check boc image
holder.checkbox.setVisibility(View.VISIBLE);
//set background color
holder.itemView.setBackgroundColor(Color.LTGRAY);
}
else
{
// when all value unselected
// hide all check box image
holder.checkbox.setVisibility(View.GONE);
// set background color
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
}
private void ClickItem(ViewHolder holder) {
// get selected item value
String s=arrayList.get(holder.getAdapterPosition());
// check condition
if(holder.checkbox.getVisibility()==View.GONE)
{
// when item not selected
// visible check box image
holder.checkbox.setVisibility(View.VISIBLE);
// set background color
holder.itemView.setBackgroundColor(Color.LTGRAY);
// add value in select array list
selectList.add(s);
}
else
{
// when item selected
// hide check box image
holder.checkbox.setVisibility(View.GONE);
// set background color
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
// remove value from select arrayList
selectList.remove(s);
}
// set text on view model
mainViewModel.setText(String.valueOf(selectList.size()));
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// initialize variables
TextView textView;
ImageView checkbox;
public ViewHolder(@NonNull View itemView) {
super(itemView);
// assign variables
textView=itemView.findViewById(R.id.text_view);
checkbox=itemView.findViewById(R.id.check_box);
}
}
}
Java
package com.example.multiple_item_delete;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class MainViewModel extends ViewModel {
// initialize variables
MutableLiveData mutableLiveData=new MutableLiveData<>();
// create set text method
public void setText(String s)
{
// set value
mutableLiveData.setValue(s);
}
// create get text method
public MutableLiveData getText()
{
return mutableLiveData;
}
}
按照路径 app > res > 布局 > 右键单击 > 新建 > 布局资源文件并创建一个名为item_main.xml 的新文件。在 item_main.xml 文件中使用以下代码 -
XML
按照路径 app > res > 右键单击 > 新建 > android 资源文件 > 资源类型 > 菜单并创建一个名为 menu.xml 的新文件。在 menu.xml 文件中使用以下代码 -
XML
第 5 步:使用Java文件
转到MainActivity。 Java文件并参考以下代码。下面是MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。
Java
package com.example.multiple_item_delete;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
// initialize variables
RecyclerView recyclerView;
TextView tvEmpty;
ArrayList arrayList=new ArrayList<>();
MainAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// assign variable
recyclerView=findViewById(R.id.recycler_view);
tvEmpty=findViewById(R.id.tv_empty);
// add values in arraylist
arrayList.addAll(Arrays.asList("One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven"
,"Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen","Twenty"));
// set layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Initialize adapter
adapter=new MainAdapter(this,arrayList,tvEmpty);
// set adapter
recyclerView.setAdapter(adapter);
}
}
按照路径 app > Java > com.example.multiple_item_delete > 右键单击 > new > Java类并创建一个名为 MainAdapter 的新文件。Java在 MainAdapter 中使用以下代码。 Java文件——
Java
package com.example.multiple_item_delete;
import android.app.Activity;
import android.graphics.Color;
import android.text.Layout;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainAdapter extends RecyclerView.Adapter {
// initialize variables
Activity activity;
ArrayList arrayList;
TextView tvEmpty;
MainViewModel mainViewModel;
boolean isEnable=false;
boolean isSelectAll=false;
ArrayList selectList=new ArrayList<>();
// create constructor
public MainAdapter(Activity activity,ArrayList arrayList,TextView tvEmpty)
{
this.activity=activity;
this.arrayList=arrayList;
this.tvEmpty=tvEmpty;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// initialize variables
View view= LayoutInflater.from(parent.getContext()).
inflate(R.layout.item_main,parent,false);
// initialize view Model
mainViewModel= ViewModelProviders.of((FragmentActivity) activity)
.get(MainViewModel.class);
// return view
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// set text on text view
holder.textView.setText(arrayList.get(position));
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// check condition
if (!isEnable)
{
// when action mode is not enable
// initialize action mode
ActionMode.Callback callback=new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// initialize menu inflater
MenuInflater menuInflater= mode.getMenuInflater();
// inflate menu
menuInflater.inflate(R.menu.menu,menu);
// return true
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// when action mode is prepare
// set isEnable true
isEnable=true;
// create method
ClickItem(holder);
// set observer on getText method
mainViewModel.getText().observe((LifecycleOwner) activity
, new Observer() {
@Override
public void onChanged(String s) {
// when text change
// set text on action mode title
mode.setTitle(String.format("%s Selected",s));
}
});
// return true
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// when click on action mode item
// get item id
int id=item.getItemId();
// use switch condition
switch(id)
{
case R.id.menu_delete:
// when click on delete
// use for loop
for(String s:selectList)
{
// remove selected item list
arrayList.remove(s);
}
// check condition
if(arrayList.size()==0)
{
// when array list is empty
// visible text view
tvEmpty.setVisibility(View.VISIBLE);
}
// finish action mode
mode.finish();
break;
case R.id.menu_select_all:
// when click on select all
// check condition
if(selectList.size()==arrayList.size())
{
// when all item selected
// set isselectall false
isSelectAll=false;
// create select array list
selectList.clear();
}
else
{
// when all item unselected
// set isSelectALL true
isSelectAll=true;
// clear select array list
selectList.clear();
// add value in select array list
selectList.addAll(arrayList);
}
// set text on view model
mainViewModel.setText(String .valueOf(selectList.size()));
// notify adapter
notifyDataSetChanged();
break;
}
// return true
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// when action mode is destroy
// set isEnable false
isEnable=false;
// set isSelectAll false
isSelectAll=false;
// clear select array list
selectList.clear();
// notify adapter
notifyDataSetChanged();
}
};
// start action mode
((AppCompatActivity) v.getContext()).startActionMode(callback);
}
else
{
// when action mode is already enable
// call method
ClickItem(holder);
}
// return true
return true;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// check condition
if(isEnable)
{
// when action mode is enable
// call method
ClickItem(holder);
}
else
{
// when action mode is not enable
// display toast
Toast.makeText(activity,"You Clicked"+arrayList.get(holder.getAdapterPosition()),
Toast.LENGTH_SHORT).show();
}
}
});
// check condition
if(isSelectAll)
{
// when value selected
// visible all check boc image
holder.checkbox.setVisibility(View.VISIBLE);
//set background color
holder.itemView.setBackgroundColor(Color.LTGRAY);
}
else
{
// when all value unselected
// hide all check box image
holder.checkbox.setVisibility(View.GONE);
// set background color
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
}
private void ClickItem(ViewHolder holder) {
// get selected item value
String s=arrayList.get(holder.getAdapterPosition());
// check condition
if(holder.checkbox.getVisibility()==View.GONE)
{
// when item not selected
// visible check box image
holder.checkbox.setVisibility(View.VISIBLE);
// set background color
holder.itemView.setBackgroundColor(Color.LTGRAY);
// add value in select array list
selectList.add(s);
}
else
{
// when item selected
// hide check box image
holder.checkbox.setVisibility(View.GONE);
// set background color
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
// remove value from select arrayList
selectList.remove(s);
}
// set text on view model
mainViewModel.setText(String.valueOf(selectList.size()));
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// initialize variables
TextView textView;
ImageView checkbox;
public ViewHolder(@NonNull View itemView) {
super(itemView);
// assign variables
textView=itemView.findViewById(R.id.text_view);
checkbox=itemView.findViewById(R.id.check_box);
}
}
}
按照路径 app > Java > com.example.multiple_item_delete > 右键单击 > new > Java class 并创建一个名为 MainViewModel 的新文件。Java在MainViewModel 中使用以下代码。 Java文件——
Java
package com.example.multiple_item_delete;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class MainViewModel extends ViewModel {
// initialize variables
MutableLiveData mutableLiveData=new MutableLiveData<>();
// create set text method
public void setText(String s)
{
// set value
mutableLiveData.setValue(s);
}
// create get text method
public MutableLiveData getText()
{
return mutableLiveData;
}
}
输出:
这是我们应用程序的最终输出。