今天就复习一下简单的CheckBox吧~~
1、什么是CheckBox:
CheckBox即是我们常见的复选框,它有两种状态,选中为true,未选中为false。常见的应用是多项选择,比如在选择兴趣爱好时,可以选中多个选项。
2、效果图。如下图所示
–>
3、CheckBox的常用属性:
android:checked=”false”
4、代码实现:
(1)在布局文件中添加CheckBox并设置有关属性
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:text="篮球"
android:textSize="20sp" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="足球"
android:textSize="20sp" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="羽毛球"
android:textSize="20sp" />
(2)回到MainActivity添加逻辑代码,完整代码如下:
public class MainActivity extends Activity implements OnCheckedChangeListener{
private CheckBox checkBox1;
private CheckBox checkBox2;
private CheckBox checkBox3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化checkBox
checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
checkBox2 = (CheckBox)findViewById(R.id.checkBox2);
checkBox3 = (CheckBox)findViewById(R.id.checkBox3);
//通过设置checkBox的监听事件来对checkBox处理,判断其是否被选中
//需要注意的是,CheckBox的监听事件与ToggleButton一样是onCheckedChangeListener而不是onClickListener
checkBox1.setOnCheckedChangeListener(this);
checkBox2.setOnCheckedChangeListener(this);
checkBox3.setOnCheckedChangeListener(this);
}
/*
*buttonView---指被选中的控件
*isChecked---指控件的状态
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 首先判断是否被选中
if(isChecked){
//获得checkBox的文本内容并用Toast打出来
String text = buttonView.getText().toString();
Toast.makeText(MainActivity.this, "你选择了"+text, Toast.LENGTH_SHORT).show();
}
}
}