Android中的CheckBox

来源:互联网 发布:adblock mac 编辑:程序博客网 时间:2024/05/21 14:46

        Android中提供了一个多选组件CheckBox,实现多选操作,因为可以多选,所以他区别于RadioButton没有了组的概念,要监听用户操作的话需要对每一个CheckBox监听。Android developers里的描述为:public class CheckBox extends CompoundButton,在CompoundButton里有监听方法:

voidsetOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener)
Register a callback to be invoked when the checked state of this button changes.

因此可通过覆写CompoundButton类中的setOnCheckedChangeListener()方法来实现对CheckBox的监听

      《Google Android 应用开发全程实录》(裴佳迪等著)第78页对CheckBox的监听操作为check_button.setOnCheckedChangeListener(new OnCheckChangedListener(){}),这样编译器会一直报错,“OnCheckedChangeListener(){} must implement the inherited abstract method RadioGroup",因为OnCheckedChangeListener()方法是用来监听RaioGroup的。正确的监听操作应为:check_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {})。或者也可使用check_button.setOnClickListener(new OnClickListener() {});来监听。代码如下:

    final CheckBox check_button = (CheckBox)findViewById(R.id.checkBox);    check_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {    // TODO Auto-generated method stub    TextView tv = (TextView)findViewById(R.id.text);    tv.setText(check_button.isChecked() ? "This option is checked" : "This option is not checked");    }    });

或者

    check_button.setOnClickListener(new OnClickListener() {    public void onClick(View v) {    // TODO Auto-generated method stub    TextView tv = (TextView)findViewById(R.id.text);    tv.setText(check_button.isChecked() ? "This option is checked" : "This option is not checked");    }});


 

原创粉丝点击