《安卓》一个按钮实现全选和全不选

来源:互联网 发布:java ireport 打印 编辑:程序博客网 时间:2024/05/18 06:24

目的描述:


在一个activity上显示三个不同名字的按钮,并设置一个名字为全选的按钮,当对它点击可以选择其余所有按钮,再次点击则取消所选的按钮。


截图展示:


单个选择

点击全选后全部选择



思路整理记录:


1.在res/layout下的布局文件activity_main.xml中定义控件(包括id,按钮文本内容等属性)

<CheckBox         android:id="@+id/eatId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="吃饭吧!"/>        <CheckBox         android:id="@+id/sleepId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="睡觉吧!"/>    <CheckBox         android:id="@+id/gameId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="lol"/>    <CheckBox         android:id="@+id/allId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="全选!"/>


2.在MainActivity.java中分别定义出每个私有的控件

<span style="white-space:pre"></span>private CheckBox eatBox;private CheckBox sleepBox;private CheckBox lolBox;private CheckBox allBox;


3.在OnCreate方法中获取按钮ID

<span style="white-space:pre"></span>eatBox = (CheckBox)findViewById(R.id.eatId);sleepBox = (CheckBox)findViewById(R.id.sleepId);lolBox = (CheckBox)findViewById(R.id.gameId);allBox = (CheckBox)findViewById(R.id.allId);


4.定义类class AllBoxCheckListener 并添加方法检测按钮是否被选中

class AllBoxCheckListener implements OnCheckedChangeListener{@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {}

5.将多选按钮与第4部中定义类的方法绑定

<span style="white-space:pre"></span>AllBoxCheckListener listener = new AllBoxCheckListener();allBox.setOnCheckedChangeListener(listener);


6.在AllBoxCheckListener类中onCheckedChanged方法检测出全选按钮是否被选中,用if_else判断然后去去设置按钮状态


public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if(isChecked){eatBox.setChecked(true);sleepBox.setChecked(true);lolBox.setChecked(true);}else{eatBox.setChecked(false);sleepBox.setChecked(false);lolBox.setChecked(false);}}}


7.简化一下设置按钮状态


public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {eatBox.setChecked(isChecked);sleepBox.setChecked(isChecked);lolBox.setChecked(isChecked);}




仅仅用来整理一下自己的思路 




0 0
原创粉丝点击