Android编程Checkbox复选框提示操作

来源:互联网 发布:竹笛教学的软件 编辑:程序博客网 时间:2024/05/22 04:50

如题复选框,即可以同时选中多个选项,至于获得选中的值,同样有两种方式: 

1.为每个CheckBox添加事件:setOnCheckedChangeListener 

2.弄一个按钮,在点击后,对每个checkbox进行判断:isChecked();

首先布局,记住为每个控件设置id

 <RadioGroup        android:layout_width="wrap_content"        android:layout_height="wrap_content">        <CheckBox            android:id="@+id/cb_one"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="篮球"/>        <CheckBox            android:id="@+id/cb_two"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="羽毛球"/>        <CheckBox            android:id="@+id/cb_three"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="足球"/>    </RadioGroup>
然后Java代码部分根据ID获取每个控件设置多选改变监听事件和点击按钮点击事件

protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        cb_one = (CheckBox) findViewById(R.id.cb_one);        cb_two = (CheckBox) findViewById(R.id.cb_two);        cb_three = (CheckBox) findViewById(R.id.cb_three);        btn_send = (Button) findViewById(R.id.btn_send);//获取控件        cb_one.setOnCheckedChangeListener(this);        cb_two.setOnCheckedChangeListener(this);        cb_three.setOnCheckedChangeListener(this);//设置监听改变事件        btn_send.setOnClickListener(this);//设置点击监听事件    }    @Override//编辑监听多选改变事件,isChecked()表示获取多选按钮状态    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {        if(compoundButton.isChecked()) Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_SHORT).show();    }    @Override//编辑点击事件    public void onClick(View view) {        String choose = "";        if(cb_one.isChecked())choose += cb_one.getText().toString() + "";        if(cb_two.isChecked())choose += cb_two.getText().toString() + "";        if(cb_three.isChecked())choose += cb_three.getText().toString() + "";        Toast.makeText(this,choose,Toast.LENGTH_SHORT).show();    }

提示:在复制代码时直接修改ID使之与xml对应就行了

运行结果:




1 0