Android复选框之鱼和熊掌可兼得CheckBox
选一个是一个
全选也可以
布局文件:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请选择你喜欢的水果:"
android:textSize="23dp"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="香蕉"
android:id="@+id/cb_one" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="苹果"
android:id="@+id/cb_two" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="菠萝"
android:id="@+id/cb_three" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交"
android:id="@+id/btn_send" />
</LinearLayout>
展示视图控制文件:MainActivity
package com.example.lenovo.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
private CheckBox cb_one;
private CheckBox cb_two;
private CheckBox cb_three;
private Button btn_send;
@Override
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
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();
}
}
本文参考学习引用:http://blog.csdn.net/coder_pig/article/details/47035625