常见控件(RadioButton、CheckBox、Toast)
1. RadioGroup和RadioButton
2.CheckBox
3.Toast(吐司)
RadioButton怎么玩
将多个RadioButton定义在一个RadioGroup里面,同一个组中的单选按钮只能选中一个。如:男,女
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/female"/>
</RadioGroup>
接下来在.java里面设置监听器,设置的监听器是给RadioGroup的
onCheckedChangeListener()
//设置监听器
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.male){
Toast.makeText(MainActivity.this,"选中了男",Toast.LENGTH_SHORT).show();
}else if (checkedId ==R.id.female){
Toast.makeText(MainActivity.this,"选中了女",Toast.LENGTH_SHORT).show();
}
}
});
CheckBox
多项选择:吃饭、睡觉、打豆豆
CheckBox和RadioGroup不同,他要为每个选项分别设置监听器
注:由于CheckBox是CompoundButton的子类,所以可以new一个CompoundButton类型(向上转型)的
监听器,而RadioGroup不是这个的子类,所以,RadioGroup定义内部类实现相同名字的监听器以适应自己的需求。
//分别设置CheckBox的监听器
checkBoxEat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(MainActivity.this,"真贪吃",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"不贪吃",Toast.LENGTH_SHORT).show();
}
}
});
checkBoxSleep.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(MainActivity.this,"真贪睡",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"不贪睡",Toast.LENGTH_SHORT).show();
}
}
});
checkBoxPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(MainActivity.this,"真贪玩",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"不贪玩",Toast.LENGTH_SHORT).show();
}
}
});