1.设置文字在下边的RadioButton
<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:text="男孩"
android:button="@null"
android:gravity="center"
android:textColor="@color/black"
android:drawableTop="@drawable/ic_launcher"
android:checked="true" />
主要代码为 android:button="@null"
、android:drawableTop="@drawable/ic_launcher"
可以看到 drawableTop、drawableBottom、drawableLeft、drawableRight 可以用来随意设置位置来实现文字的位置。
2.设置RadioButton选中时的样式
在drawable中创建一个select.xml,加入以下代码即可。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_select_sex_male_p" android:state_checked="true" />
<item android:drawable="@drawable/ic_select_sex_male_n" android:state_checked="false" />
</selector>
使用方法
<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:button="@null"
android:checked="true"
android:drawableTop="@drawable/select"
android:gravity="center"
android:text="男孩"
android:textColor="@color/black" />
3.建立RadioGroup中的RadioButton
初始化控件
private void setUpView() {
rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
rb_sex_male = (RadioButton) findViewById(R.id.rb_sex_male);
rb_sex_female = (RadioButton) findViewById(R.id.rb_sex_female);
}
获取对应RadioButton的点击事件(默认值可以设置)
private void setRadioGroupOnCheckedChangeListener() {
rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == rb_sex_male.getId()) {
} else (checkedId == rb_sex_female.getId()) {
}
}
});
}
xml布局
<RadioGroup
android:id="@+id/rg_sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/rb_sex_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:button="@null"
android:checked="true"
android:drawableTop="@drawable/a"
android:gravity="center"
android:text="男孩"
android:textColor="@color/black" />
<RadioButton
android:id="@+id/rb_sex_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:button="@null"
android:drawableTop="@drawable/b"
android:text="女孩"
android:textColor="@color/black" />
</RadioGroup>