安卓RecyclerView长按进入多选模式删除子条目(DataBinding+ActionMode实现)
先看看我们要实现的效果图:
实现思路:
- 在RecyclerView的子条目布局前面添加一个Checkbox并且默认不隐藏(gone)
- 当RecyclerView的子条目长按时触发Activity的startActionMode事件,并显示隐藏的CheckBox
- 用一个List来存储每个条目的是否被选中的状态
- 当点击”全选”或者”删除”选项时触发Adapter的相应的方法完成对子条目的选取和删除
代码实现:
Activity布局代码:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="presenter"
type="com.njp.actionmodedemo.MainActivity.Presenter"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="10dp" />
</LinearLayout>
</layout>
整个项目采用DataBinding实现,所以布局最外层是layout标签。整个Activity的布局非常简单,就只有一个RecyclerView。
Activity代码:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding mBinding;
private ActionModeAdapter mAdapter;
private Presenter mPresenter;
@Override
protected void onCreate(Bundle savedIn