android 取得按钮的值,Android进阶之RadioButton选中值的获取
时间: 2024-02-18 11:03:15 浏览: 30
在Android中,要获取RadioButton的选中值,可以使用RadioGroup和RadioButton两个控件配合使用。具体步骤如下:
1. 在布局文件中使用RadioGroup和RadioButton控件:
```xml
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton1" />
<RadioButton
android:id="@+id/radio_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton2" />
</RadioGroup>
```
2. 在Java代码中获取RadioGroup控件和选中的RadioButton控件:
```java
RadioGroup radioGroup = findViewById(R.id.radio_group);
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = findViewById(selectedId);
String selectedValue = radioButton.getText().toString();
```
其中,getCheckedRadioButtonId()方法可以获取当前选中的RadioButton的id,而findViewById()方法则可以根据id获取对应的RadioButton控件。最后,通过getText()方法获取RadioButton的文本内容,就可以得到选中的值了。