如何实现CheckBox

507 查看

下面来记载一下怎样实现CheckBox
java文件

 public class MainActivity extends Activity{
    private CheckBox checkBox;
    @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkBox = (CheckBox) findViewById(R.id.checkBox1);
     //通过设置checkbox的监听事件来对checkbox处理
    checkBox.setOnCheckedChangeListener(new  CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean  isChecked) {
            //通过oncheckchangelistener方法监听当前的checkbox是否被选中
            if(isChecked){
            //如果为true,获取checkbox的文本内容
            String tx = checkBox.getText().toString();
            Log.i("tag", tx);
            }
        }
    });

xml文件

 <CheckBox
    android:checked="false"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="篮球"
    android:textStyle="bold|italic"
    android:id="@+id/checkBox1"/>
  }