关于IOS分段选择器的样式已经不再陌生,现在百度到处都是
网上有一些开源库以及一些其它的实现方法.暂时先记录下自己实现的建议方式;
要实现如上图所示的效果,需要用横向的RadioGroup,以及自定义RadioButton样式.但是RadioButton由于左端\中间\右端三个样式不一样,因此需要自定3种RadioButton样式.每个RadioButton有两种状态,选中和未选中.我们可以用Selector文件来实现.
例如,左端的自定义的RadioButton样式
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<layer-list>
<!--layer-list将item所画的drawable一层层盖在上面-->
<item>
<shape>
<corners
android:topLeftRadius="20dp"
android:bottomLeftRadius="20dp"
/>
<solid android:color="@color/press" />
<padding
android:bottom="2px"
android:left="2px"
android:right="1px"
android:top="2px" />
</shape>
</item>
<item >
<shape >
<corners
android:topLeftRadius="19dp"
android:bottomLeftRadius="19dp"
/>
<solid android:color="@color/nomal"/>
</shape>
</item>
</layer-list>
</item>
<item android:state_checked="true">
<layer-list>
<item>
<shape>
<corners
android:topLeftRadius="20dp"
android:bottomLeftRadius="20dp"
/>
<solid android:color="@color/press" />
</shape>
</item>
</layer-list>
</item>
</selector>
可以看到<selector>下包含两个<item>,分别对应state_checked="true"选中和state_checked="false"未选中状态。<layer-list>标签下面是利用shape画的图像(radioButton的背景).<layer-list>下的item是一张图片.有多个item的话是将每个item对应的图片自下而上依次堆叠起来... 要注意,上下堆叠的两张图corner不要写一样,因为拐角的变化不和直线一样均匀,最好是上面的corner角度,比下面的角度要小一点,这样看起来效果更好.
正常状态下,的RadioButton实际是由两张图片堆叠而成,底部是颜色较深的选中状态的颜色,@color/press.然后设置一定padding后绘制较小的一部分区域,即正常显示的区域.由于底部的图片比较大,上面的不能完全盖住会在四周留下一部分边沿,看上去就是周围的边框
<span style="white-space:pre"> </span><padding
android:bottom="2px"
android:left="2px"
android:right="1px"
android:top="2px" />
预留的空间,2px,1px就是想要显示的边线的粗细,可以自己调节.但是要注意,4周留的空间不能相同..,如果左边4周都留下2px,中间4周也留下2px,两段相连的地方就会有4px的间距,看上去就显得分割线变得很粗.为了显示线条一致.需要自己注意在连接的地方预留空白只有其他方向的一半.比如,左端设置右边的空白为1px,中间设置左右两边的空白为1px.右端设置左边的空白为1px.
使用时和正常RadioGroup使用一样,只需要自己注意RadioButton的样式对应就好.
<RadioGroup
android:id="@+id/radio_group_test"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_gravity="bottom"
android:orientation="horizontal"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_button_test_001"
android:layout_width="100dp"
android:layout_height="48dp"
android:text="选项1"
android:button="@null"
android:gravity="center"
android:background="@drawable/select_radiobutton_left" />
<RadioButton
android:id="@+id/radio_button_test_002"
android:layout_width="100dp"
android:layout_height="48dp"
android:text="选项2"
android:button="@null"
android:gravity="center"
android:background="@drawable/select_radiobutton_mid" />
<RadioButton
android:id="@+id/radio_button_test_003"
android:layout_width="100dp"
android:layout_height="48dp"
android:text="选项3"
android:button="@null"
android:gravity="center"
android:background="@drawable/select_radiobutton_right" />
</RadioGroup>
要注意左中右对应的drawable文件不能写错.
最后实现效果图:
看着效果还可以.有需要的话可以下载下来自己试试看.
本文介绍了一种自定义Android中RadioGroup样式的方法,使其具备类似iOS分段选择器的视觉效果。通过自定义RadioButton样式并结合使用layer-list和shape元素,实现了不同状态下的按钮外观变化。
773

被折叠的 条评论
为什么被折叠?



