Android CheckBox 多选以及反选清除已选项

编程入门 行业动态 更新时间:2024-10-26 08:22:45

Android CheckBox <a href=https://www.elefans.com/category/jswz/34/1749019.html style=多选以及反选清除已选项"/>

Android CheckBox 多选以及反选清除已选项

前言

疫情随着这个春天的到来已悄然离去,你还记得填写问卷调查的那个时候么

话不多少,这篇文章要实现的就是一个问卷调查列表,即 Listview 嵌套 Listview 实现 checkbox 多选以及反选清除已选项

                                              

正文

思路就是定义一个 Map 集合用于存储每一个 checkbox 条目的选中状态。默认 checkbox 状态都为 false,遍历集合,选中哪条就把该条目的位置添加进集合,并设置状态为true,未选设置状态为 false,如果集合不为空设置checkbox 状态为 true ,反之为 false

1.引入库

implementation 'com.google.code.gson:gson:2.2.2'

2.准备数据

  新建一个DataJson 类 ,把接口数据定义为一个不可改变的字符串JSON

public class DataJson {public static final String JSON = "{\n" +"    \"data\": {\n" +"        \"problems\": [\n" +"            {\n" +"                \"bodydetails\": [\n" +"                    {\n" +"                        \"ConditionName\": \"发热\",\n" +"                        \"ConditionValue\": \"10\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"干咳\",\n" +"                        \"ConditionValue\": \"11\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"腹泻\",\n" +"                        \"ConditionValue\": \"12\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"身体无异常\",\n" +"                        \"ConditionValue\": \"100\"\n" +"                    }\n" +"                ],\n" +"                \"problem\": \"身体是否出现以下状况:\"\n" +"            },\n" +"            {\n" +"                \"bodydetails\": [\n" +"                    {\n" +"                        \"ConditionName\": \"划伤\",\n" +"                        \"ConditionValue\": \"10\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"水泡\",\n" +"                        \"ConditionValue\": \"11\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"疱疹\",\n" +"                        \"ConditionValue\": \"12\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"手掌无异常\",\n" +"                        \"ConditionValue\": \"100\"\n" +"                    }\n" +"                ],\n" +"                \"problem\": \"手掌是否出现以下状况:\"\n" +"            },\n" +"            {\n" +"                \"bodydetails\": [\n" +"                    {\n" +"                        \"ConditionName\": \"口腔溃疡\",\n" +"                        \"ConditionValue\": \"10\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"牙龈出血\",\n" +"                        \"ConditionValue\": \"11\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"扁导体发炎\",\n" +"                        \"ConditionValue\": \"12\"\n" +"                    },\n" +"                    {\n" +"                        \"ConditionName\": \"口腔无异常\",\n" +"                        \"ConditionValue\": \"100\"\n" +"                    }\n" +"                ],\n" +"                \"problem\": \"口腔是否出现以下状况:\"\n" +"            }\n" +"        ]\n" +"    },\n" +"    \"msg\": \"获取成功\",\n" +"    \"status\": \"Y\"\n" +"}";
}

当拿到服务器返回的数据的时候,我也是一脸懵,为什么每一项的状态码都是一样的?这怎么区分存储呢,所以嘛跟后台打好关系还是比较重要的,不然你会做很多工作,这里就自己定义实体类加 flag 标识吧,创建 ResponseBean 实体类 并新增 flag 字段

public class ResponseBean {/*** status : Y* msg : 获取成功* data : {"problems":[{"bodydetails":[{"ConditionName":"发热","ConditionValue":"10"},{"ConditionName":"干咳","ConditionValue":"11"},{"ConditionName":"腹泻","ConditionValue":"12"},{"ConditionName":"身体无异常","ConditionValue":"100"}],"problem":"身体是否出现以下状况:"},{"bodydetails":[{"ConditionName":"划伤","ConditionValue":"10"},{"ConditionName":"水泡","ConditionValue":"11"},{"ConditionName":"疱疹","ConditionValue":"12"},{"ConditionName":"手掌无异常","ConditionValue":"100"}],"problem":"手掌是否出现以下状况:"},{"bodydetails":[{"ConditionName":"口腔溃疡","ConditionValue":"10"},{"ConditionName":"牙龈出血","ConditionValue":"11"},{"ConditionName":"扁导体发炎","ConditionValue":"12"},{"ConditionName":"口腔无异常","ConditionValue":"100"}],"problem":"口腔是否出现以下状况:"}]}*/private String status;private String msg;private DataBean data;@Overridepublic String toString() {return "ResponseBean{" +"status='" + status + '\'' +", msg='" + msg + '\'' +", data=" + data +'}';}public String getStatus() {return status;}public void setStatus(String status) {this.status = status;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public DataBean getData() {return data;}public void setData(DataBean data) {this.data = data;}public static class DataBean {private List<ProblemsBean> problems;@Overridepublic String toString() {return "DataBean{" +"problems=" + problems +'}';}public List<ProblemsBean> getProblems() {return problems;}public void setProblems(List<ProblemsBean> problems) {this.problems = problems;}public static class ProblemsBean {/*** bodydetails : [{"ConditionName":"发热","ConditionValue":"10"},{"ConditionName":"干咳","ConditionValue":"11"},{"ConditionName":"腹泻","ConditionValue":"12"},{"ConditionName":"身体无异常","ConditionValue":"100"}]* problem : 身体是否出现以下状况:*/private String problem;private List<BodydetailsBean> bodydetails;@Overridepublic String toString() {return "ProblemsBean{" +"problem='" + problem + '\'' +", bodydetails=" + bodydetails +'}';}public String getProblem() {return problem;}public void setProblem(String problem) {this.problem = problem;}public List<BodydetailsBean> getBodydetails() {return bodydetails;}public void setBodydetails(List<BodydetailsBean> bodydetails) {this.bodydetails = bodydetails;}public static class BodydetailsBean {/*** ConditionName : 发热* ConditionValue : 10*/private String ConditionName;private String ConditionValue;private String flag;@Overridepublic String toString() {return "BodydetailsBean{" +"ConditionName='" + ConditionName + '\'' +", ConditionValue='" + ConditionValue + '\'' +", flag=" + flag +'}';}public String getConditionName() {return ConditionName;}public void setConditionName(String ConditionName) {this.ConditionName = ConditionName;}public String getConditionValue() {return ConditionValue;}public void setConditionValue(String ConditionValue) {this.ConditionValue = ConditionValue;}public String getFlag() {return flag;}public void setFlag(String flag) {this.flag = flag;}}}}
}

因为接口数据为数组嵌套一个数组,如下图

这里需要解决 Listview 嵌套中 item 点击失效 或 显示不全 问题 

需要自定义一个 CustomListView 类继承父类 ListView 并重写 onMeasure 方法,进行重定义高度

public class CustomListView extends ListView {public CustomListView(Context context) {super(context);}public CustomListView(Context context, AttributeSet attrs) {super(context, attrs);}public CustomListView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int newHeightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, newHeightSpec);}
}

接下来创建标题 item 的 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:id="@+id/item_title_tv"android:layout_width="match_parent"android:layout_height="80dp"android:layout_marginTop="30dp"android:gravity="center_vertical"android:paddingStart="10dp"android:paddingLeft="10dp"android:paddingEnd="10dp"android:paddingRight="10dp"android:text="标题"android:textColor="#000000" /><com.wyc.checkbox.CustomListViewandroid:id="@+id/item_list_view"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20dp"android:divider="@null"android:dividerHeight="0dp"android:overScrollMode="never" /></LinearLayout>

在创建子选项 item 的 xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android=""xmlns:app=""android:layout_width="match_parent"android:padding="10dp"android:layout_height="100dp"><TextViewandroid:id="@+id/item_check_tv"android:layout_width="0dp"android:layout_height="wrap_content"android:text="标题"android:textColor="#000000"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toStartOf="@id/item_check_box"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><CheckBoxandroid:id="@+id/item_check_box"android:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintBaseline_toBaselineOf="@id/item_check_tv"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toEndOf="@id/item_check_tv" />
</android.support.constraint.ConstraintLayout>

接下来就是外层标题适配器,创建一个 ResponseAdapter 类并继承 BaseAdapter ,然后这里定义一个 Map 数组 用来存储选项状态码,默认所有为 false

然后再判断选项列表是否为空,不为空就加载选项适配器

public class ResponseAdapter extends BaseAdapter {private List<ResponseBean.DataBean.ProblemsBean> mDataList;private Map<String, Boolean> mCheckMap = new HashMap<>();public ResponseAdapter(List<ResponseBean.DataBean.ProblemsBean> dataList) {this.mDataList = dataList;for (ResponseBean.DataBean.ProblemsBean bean : mDataList) {for (ResponseBean.DataBean.ProblemsBean.BodydetailsBean bodydetail : bean.getBodydetails()) {mCheckMap.put(bodydetail.getFlag(), false);}}}@Overridepublic int getCount() {return mDataList.size();}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}public Map<String, Boolean> getCheckMap() {return mCheckMap;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if (convertView == null) {convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_response, null);holder = new ViewHolder(convertView);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}ResponseBean.DataBean.ProblemsBean problemsBean = mDataList.get(position);holder.itemTitleTv.setText(problemsBean.getProblem());List<ResponseBean.DataBean.ProblemsBean.BodydetailsBean> bodyList = problemsBean.getBodydetails();if (bodyList != null && bodyList.size() > 0) {holder.itemListView.setVisibility(View.VISIBLE);holder.itemListView.setAdapter(new ProblemAdapter(problemsBean.getBodydetails(), mCheckMap));} else {holder.itemListView.setVisibility(View.GONE);}return convertView;}final static class ViewHolder {TextView itemTitleTv;ListView itemListView;public ViewHolder(View view) {itemListView = view.findViewById(R.id.item_list_view);itemTitleTv = view.findViewById(R.id.item_title_tv);}}
}

接下来就是子选项的adapter ,创建 ProblemAdapter 类并继承 BaseAdapter , 顶一个 Map 数组 ,然后在 getView 当中 为 checkbox 添加 改变监听事件 ,选择就存储为 true 反之为 false , 并及时刷新适配器, 接下来就是获取选项状态码,这里是从大项开始刷选 ,状态值是自己定义的接下来会说的,默认存储都为 false ,

public class ProblemAdapter extends BaseAdapter {public static final String TAG = "ProblemAdapter";private List<ResponseBean.DataBean.ProblemsBean.BodydetailsBean> mBodyDetails;private Map<String, Boolean> mCheckMap;public ProblemAdapter(List<ResponseBean.DataBean.ProblemsBean.BodydetailsBean> bodydetails, Map<String, Boolean> checkMap) {this.mBodyDetails = bodydetails;this.mCheckMap = checkMap;Log.d(TAG, "===============================");for (String integer : mCheckMap.keySet()) {Log.d(TAG, "key= " + integer + " , value = " + mCheckMap.get(integer));}}public Map<String, Boolean> getCheckMap() {return mCheckMap;}@Overridepublic int getCount() {return mBodyDetails.size();}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {final ViewHolder holder;if (convertView == null) {convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_check_view, null);holder = new ViewHolder(convertView);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.itemCheckTv.setText(mBodyDetails.get(position).getConditionName());final ResponseBean.DataBean.ProblemsBean.BodydetailsBean bean = mBodyDetails.get(position);holder.itemCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if (isChecked) {mCheckMap.put(bean.getFlag(), true);} else {mCheckMap.put(bean.getFlag(), false);}notifyDataSetChanged();}});if (mCheckMap.get("1100")) {mCheckMap.put("110", false);mCheckMap.put("111", false);mCheckMap.put("112", false);notifyDataSetChanged();}if (mCheckMap.get("2100")) {mCheckMap.put("210", false);mCheckMap.put("211", false);mCheckMap.put("212", false);notifyDataSetChanged();}if (mCheckMap.get("3100")) {mCheckMap.put("310", false);mCheckMap.put("311", false);mCheckMap.put("312", false);notifyDataSetChanged();}if (mCheckMap != null && mCheckMap.get(bean.getFlag())) {holder.itemCheckBox.setChecked(true);} else {holder.itemCheckBox.setChecked(false);}return convertView;}final static class ViewHolder {TextView itemCheckTv;CheckBox itemCheckBox;public ViewHolder(View view) {itemCheckTv = view.findViewById(R.id.item_check_tv);itemCheckBox = view.findViewById(R.id.item_check_box);}}
}

最后就是 MainActivity 进行资源整合,先看布局,布局就是一个标题栏加一个 Listview 标题栏的 已选择项 点击方便自己测试用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="选择效果"android:textColor="#000000" /><TextViewandroid:id="@+id/checkBtn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentEnd="true"android:layout_centerVertical="true"android:layout_marginEnd="10dp"android:text="已选择项"android:textColor="#ff0000" /></RelativeLayout><Viewandroid:layout_width="match_parent"android:layout_height="0.5dp"android:background="#f2f2f2" /><ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent"android:divider="@null"android:dividerHeight="0dp"android:overScrollMode="never" /></LinearLayout>

最后就是主要整合代码,主要就是 初始化时 准备下本地数据,这里自定义状态 flag 标识,循环列表通过 i 进行递增,用于判断复选框是否选中,最后加到 mDataBeanList 中,

public class MainActivity extends AppCompatActivity {public static final String TAG = "Log_MainActivity";private List<ResponseBean.DataBean.ProblemsBean> mDataBeanList = new ArrayList<>();private ListView mListView;private ResponseAdapter mAdapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initData();mListView = findViewById(R.id.listView);mAdapter = new ResponseAdapter(mDataBeanList);mListView.setAdapter(mAdapter);TextView checkBtn = findViewById(R.id.checkBtn);checkBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Map<String, List<String>> map = checkItem();Log.d(TAG, "check map = " + map.toString());}});}/*** 获取已选项目** @return*/private Map<String, List<String>> checkItem() {Map<String, List<String>> map = new HashMap<>();if (mAdapter != null) {Map<String, Boolean> checkMap = mAdapter.getCheckMap();for (ResponseBean.DataBean.ProblemsBean problemsBean : mDataBeanList) {List<String> problemList = new ArrayList<>();for (ResponseBean.DataBean.ProblemsBean.BodydetailsBean bodydetail : problemsBean.getBodydetails()) {if (checkMap.get(bodydetail.getFlag())) {problemList.add(bodydetail.getConditionValue() + "--------------" + bodydetail.getConditionName());}}map.put(problemsBean.getProblem(), problemList);}}return map;}private void initData() {ResponseBean responseBean = new Gson().fromJson(DataJson.JSON, ResponseBean.class);Log.d(TAG, "responseBean = " + responseBean.toString());List<ResponseBean.DataBean.ProblemsBean> dataList = responseBean.getData().getProblems();//准话本地数据,自定义下标,用于判断复选框是否选中for (int i = 0; i < dataList.size(); i++) {ResponseBean.DataBean.ProblemsBean problemsBean = dataList.get(i);List<ResponseBean.DataBean.ProblemsBean.BodydetailsBean> beanList = new ArrayList<>();for (int j = 0; j < problemsBean.getBodydetails().size(); j++) {//数据转化ResponseBean.DataBean.ProblemsBean.BodydetailsBean bean = problemsBean.getBodydetails().get(j);ResponseBean.DataBean.ProblemsBean.BodydetailsBean newBean = new ResponseBean.DataBean.ProblemsBean.BodydetailsBean();newBean.setConditionValue(bean.getConditionValue());newBean.setConditionName(bean.getConditionName());//自定义下标newBean.setFlag((i + 1) + bean.getConditionValue());beanList.add(newBean);}problemsBean.setBodydetails(beanList);mDataBeanList.add(problemsBean);}Log.d(TAG, "data bean list = " + mDataBeanList.toString());}
}

运行程序,敲完收工  代码后续上传,如有疑问请评论留言第一时间回复

更多推荐

Android CheckBox 多选以及反选清除已选项

本文发布于:2024-03-08 07:57:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1720277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多选   选项   Android   CheckBox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!