title: Android——ListView使用ActionMode实现的上下文长按多选菜单
date: 2019/5/25 星期六 21:54:47
tags: CSDN迁移
操作环境:Android Studio 以及自带的模拟器,相关配置如下
话不多说,先上运行截图。
第一张是初始应用的菜单界面,上方标题是可变的,可以在AndroidManifest文件中更改。对每一个列表选项,左边是安卓机器人图标,右边是选项名,这都是可以自定义,甚至可以设置主副标题等,主要看需求。
第二张是长按选中之后的操作界面。由图中可以看出,长按之后,选中项会标绿(ps:原谅我这渣渣的审美),并且上面标题菜单栏会显示选中了几项,出现三个选项,分别是返回,全部选中和删除。这个菜单是可以定制的,我这边三个选项都设置成了返回,毕竟只是为了实现这个长按多选菜单(请允许我偷个懒)。
所涉及到的相关知识
可参考:https://developer.android.google.cn/guide/topics/ui/menus.html
- ActionMode
- ListView的自定义适配器
实现部分。
首先,看看项目目录,由于我是和其他功能一起实现的,所以并不是一个独立的项目,图中相应标红框内的就是相关文件。
布局和菜单文件
第一个是activity_problem04.xml,也就是这个的主界面,用的是默认的约束布局。只有一个ListView,值得一提的是要将choiceMode设置为multipleChoiceModal,也就是可以为多选。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".problem04">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="0dp">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="multipleChoiceModal"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
AS中的设计视图如下,