【Android之单选按钮】RadioButton
单选按钮必须包含在RadioGroup中,相当于放在盒子里,为RadioGroup设置id为:nan_rsp;两个按钮设置id为:nan_rg_boy、nan_rg_girl。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="【单选按钮RadioButton的使用】:"
android:textSize="26sp"
android:textColor="#EF3C00"
android:textStyle="italic"
android:layout_marginBottom="20dp"/>
<RadioGroup
android:id="@+id/nan_rgp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/nan_rg_boy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:textSize="24sp"/>
<RadioButton
android:id="@+id/nan_rg_girl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:textSize="24sp"/>
</RadioGroup>
<TextView
android:id="@+id/nan_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
Activity中的代码如下:
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;//声明单选按钮变量
private TextView textView;//声明显示的变量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//将声明的变量绑定按钮的id
radioGroup=findViewById(R.id.nan_rgp);
textView=findViewById(R.id.nan_show);
//利用setOnCheckedChangeListener()为radioGroup建立监听
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//判断点击的是哪个radioGroup
if(checkedId==R.id.nan_rg_boy){
textView.setText("你选择的性别是:男");
}else{
textView.setText("你选择的性别是:女");
}
}
});
}
}
结果图:
初始化图:
选择后:
结论:单选需要放在一个盒子里(RadioGroup)里,然后再Activity中为“盒子”建立监听(setOnCheckendChangeListenter())。