1、RadioButton(单选)
布局代码
<RadioGroup
android:id="@+id/sexGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sex" />
<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>
Activity代码
//设置是否选中
((RadioButton) findViewById(R.id.female)).setChecked(true);
//获取哪个被选中
int checkedId = ((RadioGroup) findViewById(R.id.sexGroup)).getCheckedRadioButtonId();
String toast;
if (checkedId == -1) {
toast = "selected nothing";
} else if (checkedId == R.id.male) {
toast = "selected male";
} else {
toast = "selected female";
}
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
2、CheckBox(多选)
界面代码
CheckBox checkboxBasketBall = (CheckBox) findViewById(R.id.checkboxBasketBall);
CheckBox checkboxFootBall = (CheckBox) findViewById(R.id.checkboxFootBall);
checkboxBasketBall.setChecked(true);
checkboxFootBall.setChecked(true);
if (checkboxBasketBall.isChecked()) {
Toast.makeText(this, "basketball checked", Toast.LENGTH_LONG).show();
}
if (checkboxFootBall.isChecked()) {
Toast.makeText(this, "football checked", Toast.LENGTH_LONG).show();
}
checkboxBasketBall.setChecked(true);
checkboxBasketBall.setButtonDrawable(R.drawable.checkbox_drawable);
checkboxFootBall.setBackgroundResource(R.drawable.checkbox_drawable);
// checkboxBasketBall.setButtonTintList(ColorStateList.valueOf(Color.BLUE));
checkboxBasketBall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(MainActivity.this, buttonView + "check changed, current checked:" + isChecked, Toast.LENGTH_LONG).show();
}
});
3、Switch
界面代码
<Switch
android:id="@+id/switchView"
android:text="@string/switchText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Activity代码
Switch switchView = (Switch) findViewById(R.id.switchView);
switchView.setChecked(true);
3、ToggleButton
界面代码
<ToggleButton
android:id="@+id/toggleButton"
android:text="@string/toggleText"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Activity代码
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setChecked(true);
isChecked = toggleButton.isChecked();
Button的常见方法
1、setChecked 设置Button的选中状态
2、setonCheckedChangeListener
设置选中状态变化事件
3、setButtonDrawable
设置Button的图标
4、setButtonTintList(5.0以后才有)
设置着色