关于RadioButton,它的具体例子嘛,就好像是QQ啊、微信之类的app底部那几个按钮,不过他们是不是用RadioButton来实现的我不太清楚,但是RadioButton基本上就是这样的效果
接下来就接着上一篇来实现一下RadioButton吧,使用RadioButton必须在RadioGroup组件中。
首先,上一篇将MainActiviy主界面替换成ContentFragment后,现在要把ContentFragment的代码重新修改一下,以便于显示RadioButton,在此之前,先创建一个ContentFragment的布局文件吧。
布局文件——content_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/content_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<RadioGroup
android:id="@+id/rd_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_dark"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rd_news"
android:text="新闻"
android:drawableTop="@drawable/rb_news_drawable_selector"
style="@style/button_tag_style"/>
<RadioButton
android:id="@+id/rd_weather"
android:text="天气"
android:drawableTop="@drawable/rb_weather_drawable_selector"
style="@style/button_tag_style"/>
<RadioButton
android:id="@+id/rd_picture"
android:text="图片"
android:drawableTop="@drawable/rb_picture_drawable_selector"
style="@style/button_tag_style"/>
<RadioButton
android:id="@+id/rd_vedio"
android:text="视频"
android:drawableTop="@drawable/rb_vedio_drawable_selector"
style="@style/button_tag_style"/>
<RadioButton
android:id="@+id/rd_shopping"
android:text="购物"
android:drawableTop="@drawable/rb_shopping_drawable_selector"
style="@style/button_tag_style"/>
</RadioGroup>
</LinearLayout>
从上面的代码其实可以很明显的看到,RadioButton位于RadioGroup中,而RadioButton是配合ViewPager来使用的,每点击一个RadioButton,就切换另外一个页面,其中有几点需要注意的。
1.整个布局是放在LinearLayout中的,因为需要用到权重,也就是weight这个属性,所以最外层的布局是LinearLayout。
2.其实点开RadioGroup会看到【public class RadioGroup extends LinearLayout{…}】,这说明RadioGroup继承的LinearLayout,所以在RadioGroup的属性里面,需要设置方向,也就是orientation的设置,由于底部按钮是一横排,这里自然是设置水平方向horizontal了。
3.你会发现每一个RadioButton的属性设置只有短短几行代码,其实是因为每个RadioButton设置的属性,有一大部分是重复的,于是将些重复的部分写在了values下的style.xml中,比如一个RadioButton原来的代码是:
<RadioButton
android:id="@+id/rd_shopping"
android:text="购物"
android:drawableTop="@drawable/rb_shopping_drawable_selector"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_gravity="center"
android:textSize="14sp"
android:gravity="center"
android:button="@null"
android:drawablePadding=