Android RadioButton自定义样式正确姿势

1. 图片示例

这里写图片描述

2.说明

在移动应用开发过程中,我们会比较多的使用RadioButton,但是好多时候并不了解怎样正确的使用它,如果充分了解到他的使用方法和好处后,你会感受到RadioButton其实是非常强大和好用的。

如果你有以下问题你可以通过这篇文章获取一些答案:

  • 给RadioButton自定义样式
  • 自定义样式后图片变形
  • 自定义样式后,再设置text属性,图片变形

3. 自定义样式

自定义样式其实挺简单,分为以下几步:

  1. 准备两张图片(选中状态和非选中状态)。
  2. 添加一个选择器
  3. 给RadioButton设置button属性为@null
  4. 设置RadioButton的background为该选择器
  5. 完成。

代码示例如下:

// 选择器
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_unchecked" android:state_checked="false"></item>
    <item android:drawable="@drawable/ic_checked"></item>
</selector>

// View布局
<RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        android:background="@drawable/selector_radio"
        android:button="@null"
        android:text="你好吗"/>
问题:

这个时候你会发现图片有些变形,但查看图片的宽和高发现图片的尺寸是正常的,但放上去确变形了。

4. 自定义样式后图片变形解决

一般情况你可以通过2种途径来解决这个问题:

  1. 给RadioButton的设置固定的宽度和高度
  2. 设置textsize为0dp。

使用这两种方法后确实会解决现有问题,but, 如果你有添加文本的需求,给它添加文字后变形问题又会出现。当然你可以RadioButton上只放图片,至于文本嘛,可以再添加一个TextView来放文本,这种方法确实可以解决添加文本后变形的问题,但是这也太麻烦了吧,人家RadioButton给你提供好了text属性让你来放置文本,你还要再写一次,多此一举。

5. text属性引起的图片变形解决

之前看网上好多种说法都是说禁用button属性,再设置background,其实这个方法并不优雅,button和background本业就是用来做两个事情的,你非得把人的button属性禁用掉,再用background来实现样式,虽然大体上也可以实现,但是这个的支持肯定不是那么好。

正确的姿势应该是把你自定义的selecter设置到button属性上,这样你再设置文本就不会出现图片变形的问题了。

这样设置以后你会发现图片与文本的间距变小了,该怎么设置呢?
答案:通过android:paddingHorizontal=”10dp”这个属性就可以很easy的设置文本与图片之间的间距。

6.总结

不要乱用background属性,自定义样式的时候给button属性设置选择器,用正确的姿势,你将省很多事。正确示例:

<RadioButton
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:paddingHorizontal="10dp"
     android:button="@drawable/selector_radio"
     android:text="你好吗"
     android:textSize="14sp"
     android:textColor="@color/black"/>

猜你喜欢

转载自blog.csdn.net/haha223545/article/details/82222982
今日推荐