over 6 years ago

做一下如果使用FragmentTabHost来做Tab进行不同内容在展示,在同一个Activity中。

FragmentTabHost布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

由于 FragmentTabHost 并不兼容Android低版本,所以需要导入一个 android.support.v4 库来支持。

设置Tab Class
mLayoutInflater = LayoutInflater.from(this);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        View mMenuTabView = mLayoutInflater.inflate(R.layout.tab_item, null);
        TextView mMenuTextView = (TextView) mMenuTabView.findViewById(R.id.textview);
        mMenuTextView.setText("菜单");
        mTabHost.addTab(
                mTabHost.newTabSpec("Menu").setIndicator(mMenuTabView), Fragment1.class, null);
        mTabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.tab_background); // 设置按钮颜色以及点击后变化

按钮布局

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white" android:state_pressed="true" /> // 点击前效果
    <item android:drawable="@color/tabSelected" android:state_selected="true" /> // 点击后效果
</selector>
每个Tab的内容
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_content_1, null);
}
效果
http://a2.qpic.cn/psb?/V12FB5eo4QLuH9/OP4AsX73trW.fNX8LbKi54m*UuoYJg.qDAVj66veE*g!/b/dItp6.HhCwAA&bo=gAJFA8gEQAYDCmE!&rf=viewer_4
← Ruby Proc 类 ViewPager with FragmentPagerAdapter →
 
comments powered by Disqus