功能
从多种选择中选择一个,需要单选按钮,经典场景是选择性别男、女。
显示
单选按钮需要放到单选按钮组RadioGroup中,每组中只有一个元素可以被选中。RadioGroup常用属性有:
- check,设置选中按钮的资源编号
- getCheckedRadioButtonId,获取选中按钮的资源编号
实例代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请选择性别"/>
<RadioGroup
android:id="@+id/radioGroupSex"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"/>
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
<Button
android:id="@+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="确认"/>
</LinearLayout>
效果:
获取选中项
点击确认按钮后,获取选中项,并弹窗提示,代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取按钮
Button buttonOk = findViewById(R.id.buttonOk);
//设置按钮点击监听器
buttonOk.setOnClickListener(new MyOnClickListener());
}
//定义按钮点击监听器
class MyOnClickListener implements View.OnClickListener {
//按钮点击
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonOk) {//被点击的是确认按钮
//获取选中项
RadioGroup radioGroup = findViewById(R.id.radioGroupSex);
String sex = "";
if (radioGroup.getCheckedRadioButtonId() == R.id.radioMale) {
sex = "男";
} else {
sex = "女";
}
//显示提示框
Toast.makeText(MainActivity.this, "你选择了:" + sex, Toast.LENGTH_SHORT).show();
}
}
}
}
效果:
监听选中项变化
当选中项发生变化时,可以监听该变化,代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup radioGroup = findViewById(R.id.radioGroupSex);
//设置监听器
radioGroup.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
}
class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener{
//用户点击单选按钮触发
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i==R.id.radioMale){
Toast.makeText(MainActivity.this, "你选择了:男", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "你选择了:女" , Toast.LENGTH_SHORT).show();
}
}
}
}
注意当选中项变化时才会触发!