RadioButton
RadioButton是android控件中的一种单选按钮,默认是圆形的,不过你也可以自定义。
<RadioButton
android:id="@+id/radio_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hobby"
android:textSize="20sp"/>
当你要自定义按钮的形状的时候,你需要把button属性设置为null
<ButtonRadio
android:button="@null"
android: background="你自定义的形状shape"/>
RadioGroup
一个RadioGroup标签可以包含多个RadioButton控件,不过只能选中一个。
<RadioGroup
android:id="@+id/rg_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="30dp">
<RadioButton
android:id="@+id/radio_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:textSize="20sp"
android:checked="true"
/>
<RadioButton
android:id="@+id/radio_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textSize="20sp"
/>
</RadioGroup>
其中checked属性是默认选中。
获取按钮信息
radioGroup2 = findViewById(R.id.rg_2);
radioButton4 = findViewById(R.id.radio_4);
radioButton5 = findViewById(R.id.radio_5);
radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
String text = null;
if(radioButton4.getId() == i) {
text = radioButton4.getText().toString();
} else {
text = radioButton5.getText().toString();
}
Toast.makeText(RadioButtonActivity.this, text, Toast.LENGTH_SHORT).show();
}
});
setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()):监听按钮组中是否有按钮被按下。
public void onCheckedChanged(RadioGroup radioGroup, int i):当有按钮选中时检测按钮的变化,其中第二个参数i记录的是选中的按钮的id属性;
radioButton4.getId(): 获取按钮的id值;
radioButton5.getText().toString():获取按钮的信息。