Android下利用RadioGroup和RadioButton实现Tabbar的效果

本实现方法主要使用RadioGroup和RadioButton的组合方式来实现Tabbar的效果。

其中选中的Tab的切换的动作可以通过RadioGroup的OnCheckedChangeListener监听事件来完成动作的响应。

tab切换事件代码如下:

RadioGroup rg = (RadioGroup) findViewById(R.id.bottom_tabbar);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                case R.id.bottom_tabbar_rb_1:
                    …
                    break;
                case R.id.bottom_tabbar_rb_2:
                    …
                    break;
                }
            }
        });

 如果要设置初始的选中item可以使用RaidoGroup的check(int id)方法。参数id指的是RadioGroup中的RadioButton的id。

tabbar对应的xml的布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/bottom_bar_height"    android:orientation="horizontal" ><!—设置横向排列 -->

    <RadioButton
        android:id="@+id/bottom_tabbar_rb_1"
       android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/bg_bottom_bar_item"<!—设置Tab的选中背景-->
        android:button="@android:color/transparent"<!—隐藏RaidoButton的图标-->
        android:drawableTop="@drawable/ic_bottom_item_home"<!—设置RadioButton的Icon-->
        android:gravity="center"
        android:text="@string/bottom_bar_item_home_text"/>

    <RadioButton
        android:id="@+id/bottom_tabbar_rb_2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/bg_bottom_bar_item"
        android:button="@android:color/transparent"
        android:drawableTop="@drawable/ic_bottom_item_notice"
        android:gravity="center"
        android:text="@string/bottom_bar_item_notice_text"/>
</RadioGroup>

 显示的效果如下:

 

posted @ 2014-05-14 14:49  铭久  阅读(11262)  评论(0编辑  收藏  举报