您的位置:首页 > 其它

CheckBox全选的实现

2015-11-30 17:02 211 查看

今天学习了CheckBox控件的一些知识:

1.用getId()方法判断选择了哪个CheckBox控件

2.用isCheck()方法判断CheckBox控件的状态

3.实现OnCheckedChange()类的方法代替实现OnClickListener()类的方法

4.要改变CheckBox控件的状态要用到setChecked()方法

实现了一个全选功能,先判断全选是不是被点击,再根据状态去执行全选和全不选。
<span style="font-size:14px;">public class MainActivity extends AppCompatActivity {
private CheckBox eatbox;
private CheckBox sleepbox;
private CheckBox codebox;
private CheckBox allbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eatbox = (CheckBox) findViewById(R.id.eat);
sleepbox = (CheckBox) findViewById(R.id.sleep);
codebox = (CheckBox) findViewById(R.id.code);
allbox = (CheckBox) findViewById(R.id.all);
CheckBoxListener checkBoxListener = new CheckBoxListener();
eatbox.setOnCheckedChangeListener(checkBoxListener);
sleepbox.setOnCheckedChangeListener(checkBoxListener);
codebox.setOnCheckedChangeListener(checkBoxListener);
allbox.setOnCheckedChangeListener(checkBoxListener);
}
class CheckBoxListener implements CompoundButton.OnCheckedChangeListener{

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.getId() == R.id.eat){
System.out.println("eat");
}else if(buttonView.getId() == R.id.sleep){
System.out.println("sleep");
}else if(buttonView.getId() == R.id.code){
System.out.println("code");
}
if(buttonView.getId() == R.id.all){
if(buttonView.isChecked() == true){
eatbox.setChecked(true);
sleepbox.setChecked(true);
codebox.setChecked(true);
}
else{
eatbox.setChecked(false);
sleepbox.setChecked(false);
codebox.setChecked(false);
}
}
}
}
</span>

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: