Android 沉淀之TabHost 【一】

最近在做一个小的软件,用到了TabHost,于是去网上查了一下资料,搜集整理加上自己的心得

实现TabHost的方法有多种,可能没有介绍完,欢迎补充:


【方案一】:

1、新建一个Activity,取名MainActivity,使MainActivity extends TabActivity


package hink.tabhost;

import android.app.TabActivity;

public class MainActivity extends TabActivity {

}

2、从父类继承OnCreate()方法    (代码略过...)


3、在AndroidManifest.xml文件中进行注册    (代码略过...)


4、为MainActivity设计一个布局文件,这里采用FrameLayout作为根布局,每一个标签也对应一个LinearLayout


<?xml version="1.0" encoding="utf-8"?>
<!--  这里是根节点布局  -- >
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

<!--  第一个Tab 对应的布局  -- >
    <LinearLayout android:id="@+id/widget_layout_Blue"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        androidrientation="vertical" >
        <EditText android:id="@+id/widget34" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="EditText"
            android:textSize="18sp">
        </EditText>
        <Button android:id="@+id/widget30" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Button">
        </Button>
    </LinearLayout>
<!--  第二个Tab 对应的布局  -- >
    <LinearLayout android:id="@+id/widget_layout_red"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        androidrientation="vertical"  >
        <AnalogClock android:id="@+id/widget36"
            android:layout_width="wrap_content" android:layout_height="wrap_content">
        </AnalogClock>
    </LinearLayout>
<!--  第三个Tab 对应的布局  -- >
    <LinearLayout android:id="@+id/widget_layout_green"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        androidrientation="vertical">
        <RadioGroup android:id="@+id/widget43"
            android:layout_width="166px" android:layout_height="98px"
            androidrientation="vertical">
            <RadioButton android:id="@+id/widget44"
                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="RadioButton">
            </RadioButton>
            <RadioButton android:id="@+id/widget45"
                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="RadioButton">
            </RadioButton>
        </RadioGroup>
    </LinearLayout>
</FrameLayout>

5、声明TabHost,然后用LayoutInflater过滤出布局来,给TabHost加上含有Tab页面的FrameLayout
private TabHost myTabhost;
myTabhost=this.getTabHost();//从TabActivity上面获取放置Tab的TabHost
LayoutInflater.from(this).inflate(R.layout.main, myTabhost.getTabContentView(), true);
//from(this)从这个TabActivity获取LayoutInflater
//R.layout.main 存放Tab布局
//通过TabHost获得存放Tab标签页内容的FrameLayout
//是否将inflate 拴系到根布局元素上
myTabhost.setBackgroundColor(Color.argb(150, 22, 70, 150));
//设置一下TabHost的颜色

6、在TabHost创建一个标签,然后设置一下标题、图标、标签页布局


myTabhost
                .addTab(myTabhost.newTabSpec("TT")// 制造一个新的标签TT
                        .setIndicator("KK",
                                getResources().getDrawable(R.drawable.ajjc))
                        // 设置一下显示的标题为KK,设置一下标签图标为ajjc
                        .setContent(R.id.widget_layout_red));
        //设置一下该标签页的布局内容为R.id.widget_layout_red,这是FrameLayout中的一个子Layout

7、标签切换事件处理,setOnTabChangedListener
myTabhost.setOnTabChangedListener(new OnTabChangeListener(){
            @Override
            public void onTabChanged(String tabId) {
                // TODO Auto-generated method stub
            }            
        });

8、各个标签页的动态MENU,这里先把在XML中设计好的MENU放到一个int数组里
 private static final int myMenuResources[] = { R.menu.phonebook_menu,
            R.menu.addphone_menu, R.menu.chatting_menu, R.menu.userapp_menu };
在setOnTabChangedListener()方法中根据标签的切换情况来设置myMenuSettingTag
@Override
    public void onTabChanged(String tagString) {
        // TODO Auto-generated method stub
        if (tagString.equals("One")) {
            myMenuSettingTag = 1;
        }
        if (tagString.equals("Two")) {
            myMenuSettingTag = 2;
        }
        if (tagString.equals("Three")) {
            myMenuSettingTag = 3;
        }
        if (tagString.equals("Four")) {
            myMenuSettingTag = 4;
        }
        if (myMenu != null) {
            onCreateOptionsMenu(myMenu);
        }
    }
然后onCreateOptionsMenu(Menu menu) 方法中通过MenuInflater过滤器动态加入MENU
   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        // Hold on to this
        myMenu = menu;
        myMenu.clear();//清空MENU菜单
        // Inflate the currently selected menu XML resource.
        MenuInflater inflater = getMenuInflater();        
//从TabActivity这里获取一个MENU过滤器
        switch (myMenuSettingTag) {
        case 1:
            inflater.inflate(myMenuResources[0], menu);
            //动态加入数组中对应的XML MENU菜单
            break;
        case 2:
            inflater.inflate(myMenuResources[1], menu);
            break;
        case 3:
            inflater.inflate(myMenuResources[2], menu);
            break;
        case 4:
            inflater.inflate(myMenuResources[3], menu);
            break;
        default:
            break;
        }
        return super.onCreateOptionsMenu(menu);
    }

到此,方案一实现完成,待续......

接着上次写:


【方案二】:

感谢  农民伯伯 

实现效果图























1、编写布局文件:maintabs.xml

<?xml version="1.0" encoding="UTF-8"?>
<TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
        <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0.0dip" android:layout_weight="1.0" />
        <TabWidget android:id="@android:id/tabs" android:visibility="gone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.0" />
        <RadioGroup android:gravity="center_vertical" android:layout_gravity="bottom" android:orientation="horizontal" android:id="@id/main_radio" android:background="@drawable/maintab_toolbar_bg" android:layout_width="fill_parent" android:layout_height="wrap_content">
            <RadioButton   android:text="@string/main_home" android:checked="true" android:id="@+id/radio_button0" android:layout_marginTop="2.0dip" android:drawableTop="@drawable/icon_1_n" style="@style/main_tab_bottom" />
            <RadioButton android:id="@+id/radio_button1" android:layout_marginTop="2.0dip" android:text="@string/main_news" android:drawableTop="@drawable/icon_2_n" style="@style/main_tab_bottom" />
            <RadioButton android:id="@+id/radio_button2" android:layout_marginTop="2.0dip" android:text="@string/main_my_info" android:drawableTop="@drawable/icon_3_n" style="@style/main_tab_bottom" />
            <RadioButton android:id="@+id/radio_button3" android:layout_marginTop="2.0dip" android:text="@string/menu_search" android:drawableTop="@drawable/icon_4_n" style="@style/main_tab_bottom" />
            <RadioButton android:id="@+id/radio_button4" android:layout_marginTop="2.0dip" android:text="@string/more" android:drawableTop="@drawable/icon_5_n" style="@style/main_tab_bottom" />
        </RadioGroup>
    </LinearLayout>
</TabHost>


2、编写布局文件:styles.xml

<style name="main_tab_bottom">
        <item name="android:textSize">@dimen/bottom_tab_font_size</item>
        <item name="android:textColor">#ffffffff</item>
        <item name="android:ellipsize">marquee</item>
        <item name="android:gravity">center_horizontal</item>
        <item name="android:background">@drawable/home_btn_bg</item>
        <item name="android:paddingTop">@dimen/bottom_tab_padding_up</item>
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:button">@null</item>
        <item name="android:singleLine">true</item>
        <item name="android:drawablePadding">@dimen/bottom_tab_padding_drawable</item>
        <item name="android:layout_weight">1.0</item>
    </style>

3、编写布局文件:home_btn_bg.xml

<selector
          xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:state_focused="true" android:state_enabled="true" android:state_pressed="false" android:drawable="@drawable/home_btn_bg_s" />
            <item android:state_enabled="true" android:state_pressed="true" android:drawable="@drawable/home_btn_bg_s" />
            <item android:state_enabled="true" android:state_checked="true" android:drawable="@drawable/home_btn_bg_d" />
            <item android:drawable="@drawable/transparent" />
        </selector>


代码说明:
1.  需要注意的是他这里把TabWidget的Visibility设置成了gone!也就是默认难看的风格不见了:,取而代之的是5个带风格的单选按钮.

2.  注意为单选按钮设置的style,其中最重要的是为其background设置了home_btn_bg.xml,也就是自定义了选中效果。

4、编写Java代码:

public class MainTabActivity extends TabActivity implements
        OnCheckedChangeListener {

    private TabHost mHost;
    private Intent mMBlogIntent;
    private Intent mMoreIntent;
    private Intent mInfoIntent;
    private Intent mSearchIntent;
    private Intent mUserInfoIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.maintabs);

        // ~~~~~~~~~~~~ 初始化
        this.mMBlogIntent = new Intent(this, HomeListActivity.class);
        this.mSearchIntent = new Intent(this, SearchSquareActivity.class);
        this.mInfoIntent = new Intent(this, MessageGroup.class);
        this.mUserInfoIntent = new Intent(this, MyInfoActivity.class);
        this.mMoreIntent = new Intent(this, MoreItemsActivity.class);

        initRadios();
        
        setupIntent();
    }

    /**
     * 初始化底部按钮
     */
    private void initRadios() {
         ((RadioButton) findViewById(R.id.radio_button0)).setOnCheckedChangeListener(this);
         ((RadioButton) findViewById(R.id.radio_button1)).setOnCheckedChangeListener(this);
         ((RadioButton) findViewById(R.id.radio_button2)).setOnCheckedChangeListener(this);
         ((RadioButton) findViewById(R.id.radio_button3)).setOnCheckedChangeListener(this);
         ((RadioButton) findViewById(R.id.radio_button4)).setOnCheckedChangeListener(this);
    }

    /**
     * 切换模块
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
            case R.id.radio_button0:
                this.mHost.setCurrentTabByTag("mblog_tab");
                break;
            case R.id.radio_button1:
                this.mHost.setCurrentTabByTag("message_tab");
                break;
            case R.id.radio_button2:
                this.mHost.setCurrentTabByTag("userinfo_tab");
                break;
            case R.id.radio_button3:
                this.mHost.setCurrentTabByTag("search_tab");
                break;
            case R.id.radio_button4:
                this.mHost.setCurrentTabByTag("more_tab");
                break;
            }
        }
    }

    private void setupIntent() {
        this.mHost = getTabHost();
        TabHost localTabHost = this.mHost;

        localTabHost.addTab(buildTabSpec("mblog_tab", R.string.main_home,
                R.drawable.icon_1_n, this.mMBlogIntent));

        localTabHost.addTab(buildTabSpec("message_tab", R.string.main_news,
                R.drawable.icon_2_n, this.mInfoIntent));

        localTabHost.addTab(buildTabSpec("userinfo_tab", R.string.main_my_info,
                R.drawable.icon_3_n, this.mUserInfoIntent));

        localTabHost.addTab(buildTabSpec("search_tab", R.string.menu_search,
                R.drawable.icon_4_n, this.mSearchIntent));

        localTabHost.addTab(buildTabSpec("more_tab", R.string.more,
                R.drawable.icon_5_n, this.mMoreIntent));

    }

    private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon,
            final Intent content) {
        return this.mHost
                .newTabSpec(tag)
                .setIndicator(getString(resLabel),
                        getResources().getDrawable(resIcon))
                .setContent(content);
    }

代码说明:

1.  由于TabWidget被隐藏,所以相关的事件也会无效,这里取巧用RadioGroup与RadioButton的特性来处理切换,然后监听事件调用setCurrentTabByTag来切换Activity。

2.  注意即使TabWidget被隐藏,也要为其设置indicator,否则会保持。

总结

    在这之前如果要做这种效果我恐怕第一时间就会想到用ActivityGroup来做,主要是因为TabHost的TabWidget非常难看,用起来也不方便。其实从源码可以看出,TabActivity也是继承自ActivityGroup,这里结合了单选按钮和TabHost,各取其长,有时间可以专门写一个这样的自定义控件




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值