Android Studio 单选按钮RadioButton
点此查看全部文字教程、视频教程、源代码
本文目录
- 1. 功能
- 2. 显示
- 3. 获取选中项
- 4. 监听选中项变化
1. 功能
从多种选择中选择一个,需要单选按钮,经典场景是选择性别男、女。
2. 显示
单选按钮需要放到单选按钮组RadioGroup中,每组中只有一个元素可以被选中。RadioGroup常用属性有:
- check,设置选中按钮的资源编号
- getCheckedRadioButtonId,获取选中按钮的资源编号
实例代码如下:
<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"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="请选择性别"/><RadioGroupandroid:id="@+id/radioGroupSex"android:layout_width="match_parent"android:layout_height="wrap_content"><RadioButtonandroid:id="@+id/radioMale"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="男"android:checked="true"/><RadioButtonandroid:id="@+id/radioFemale"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="女"/>RadioGroup><Buttonandroid:id="@+id/buttonOk"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="确认"/>
LinearLayout>
效果:

3. 获取选中项
点击确认按钮后,获取选中项,并弹窗提示,代码如下:
public class MainActivity extends AppCompatActivity {@Overrideprotected 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 {//按钮点击@Overridepublic 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();}}}
}
效果:

4. 监听选中项变化
当选中项发生变化时,可以监听该变化,代码如下:
public class MainActivity extends AppCompatActivity {@Overrideprotected 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{//用户点击单选按钮触发@Overridepublic 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();}}}
}
注意当选中项变化时才会触发!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
