Android RadioButton设置选中时文字和背景颜色同时改变

Android RadioButton设置选中时文字和背景颜色同时改变

liuwan1992 2016-09-28 10:35:04 69108 收藏 21
分类专栏: Android UI
版权
在使用 RadioButton 时,有时我们会想要达到选中时文字颜色和背景颜色同时改变的效果,这里还需要多进行几步操作。

首先,在布局文件中新建一组 RadioButton :

<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">

<RadioButton
android: 这样设置可以不显示我们通常所见的 RadioButton 中的圆形选中按钮.

2、android:background="@drawable/radiobutton_background" 这里设置了背景选择器,代码如下:


<selector xmlns:andro />
</selector>
这里面的选中样式又指向一个 Drawable 资源文件 radiobutton_background_checked.xml ,具体代码如下:

<shape xmlns:andro />
</shape>
以上这些资源文件都放在 res/drawable/ 目录下。

3、android:textColor="@color/radiobutton_textcolor" 这里设置了字体颜色选择器,需要稍作说明的是:需要在 res 目录下新建一个

文件夹取名为 color ,将字体颜色选择器 radiobutton_textcolor.xml 文件存放在 res/color/ 目录下面。代码如下:

<selector xmlns:andro />
</selector>
经过以上步骤后,我们来看一下效果图:
     

Android RadioButton设置选中时文字和背景颜色同时改变Android RadioButton设置选中时文字和背景颜色同时改变

最后提一下怎么通过 RadioGroup 获取 RadioButton :


RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
String result = radioButton.getText().toString();
}
});
这样就可以获取到当前 RadioGroup 中选中的 RadioButton ,然后进行一些你想要的操作。
————————————————
版权声明:本文为****博主「liuwan1992」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.****.net/liuwan1992/article/details/52688408

https://blog.****.net/liuwan1992/article/details/52688408