现在越来越多的app使用Tab选项卡的效果了,今天我们也来试试,上次我们说过用TextView控件来实现,但是要做选中与未选中的效果切换需要写代码来实现,比较复杂,今天我们就来用RadioGroup控件实现,更加简单和快捷。
RadioGroup控件定义如下:
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@drawable/tab_bg"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<RadioButton
android:id="@+id/radioHome"
style="@style/radioStyle"
android:checked="true"
android:drawableTop="@drawable/selector_button_home"
android:text="@string/home" />
<RadioButton
android:id="@+id/radioCar"
style="@style/radioStyle"
android:drawableTop="@drawable/selector_button_car"
android:text="@string/car" />
<RadioButton
android:id="@+id/radioAbout"
style="@style/radioStyle"
android:drawableTop="@drawable/selector_button_about"
android:text="@string/about" />
</RadioGroup>
其中,style属性,drawableTop属性和text都使用xml配置的方式来定义。
selector_button_home的定义如下(新建xml的时候要选择drawable的selector类型):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/home_select" android:state_checked="true"></item>
<item android:drawable="@drawable/home_unselect"></item>
</selector>
实现的效果是,当radioHome单选按钮选中与未选中时,自动切换按钮的图片。另外两个按钮的xml定义也一样,只不过改了图片。
style属性是将radio按钮通用的属性定义抽取出来,xml如下
<style name="radioStyle">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">1</item>
<item name="android:button">@null</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:textColor">@color/color_button</item>
<item name="android:drawablePadding">3dp</item>
<item name="android:textSize">12sp</item>
<item name="android:background">@null</item>
</style>
上面设置button属性为@null,目的是去掉radio按钮自带的那个小圆圈。
而设置background属性为@null,是为了兼容低版本的手机系统,在低版本系统里,如果不这么设置的话,RadioGroup做的按钮会偏移,原因是因为这个属性默认有一张背景图片。
而text属性也是实现了当radio按钮的文字效果在选中与未选中时自动切换效果,在新建xml的时候,要选择Color List和selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#E63B53"/>
<item android:color="#82858b"/>
</selector>
这里实现的是,选中与未选中时,切换文字的颜色。
最终效果如下(选中时,显示红色图片和文字,未选中时,显示灰色图片和文字):