RadioButton通常要配合RadioGroup使用
基础的RadioButton使用的xml代码如下
<RadioGroup
android:id="@+id/act_test_radioGroup"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
>
<RadioButton
android:id="@+id/act_test_radioBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textSize="18sp"
android:text="选项1 "
/>
<RadioButton
android:id="@+id/act_test_radioBtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="选项2"
/>
</RadioGroup>
实现的效果
去掉 按钮 ,保留文字的效果
在drawable目录下新建一个样式
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape>
<solid android:color="#6bb5af" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:state_checked="false">
<shape>
<stroke android:width="1dp" android:color="#6bb5af" />
<corners android:radius="5dp" />
</shape>
</item>
</selector>
Activity 的 xml代码为 :
<RadioGroup
android:id="@+id/act_test_radioGroup"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
>
<RadioButton
android:id="@+id/act_test_radioBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textSize="18sp"
android:text="选项1 "
android:padding="8dp"
android:gravity="center"
android:button="@null"
android:background="@drawable/selector_radiobutton"
/>
<RadioButton
android:id="@+id/act_test_radioBtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="选项2"
android:layout_marginLeft="10dp"
android:padding="8dp"
android:gravity="center"
android:background="@drawable/selector_radiobutton"
android:button="@null"
/>
</RadioGroup>
效果为
下面来添加点击监听事件
在 Java代码中添加
RadioGroup radioGroup = findViewById(R.id.act_test_radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = group.findViewById(checkedId);
Toasty.normal(MainActivity.this, radioButton.getText()).show();
}
});