美文网首页
使用FragmentTabHost+Fragment实现底部导航

使用FragmentTabHost+Fragment实现底部导航

作者: Amy_LuLu__ | 来源:发表于2018-03-12 18:06 被阅读0次

第一步:activity的布局文件

    <!--显示fragment区域-->
    <FrameLayout
        android:id="@+id/fl_main_show_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <!--底部fragmentTabHost-->
    <android.support.v4.app.FragmentTabHost
        android:id="@+id/fth_main_botton_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"/>

第二步:代码中实现

    private void initTabHost() {
        //要与那个fragment显示区域进行关联(可为viewpager)
        fthMainBottonLayout.setup(this,getSupportFragmentManager(),R.id.fl_main_show_layout);
        //去掉分隔线
        fthMainBottonLayout.getTabWidget().setDividerDrawable(null);

        //给每个Tab按钮设置标签、图标和文字 几个tab new几个
        int[] images = {R.drawable.icon_list,R.drawable.icon_circle,R.drawable.icon_user};
        Class[] clazz = {LeftFragment.class, MiddleFragment.class, RightFragment.class};
        String[] tags = {"left","middle","right"};

        for (int i = 0; i < images.length; i++) {
            Bundle bundle = new Bundle();
            bundle.putString("count",i+"");
            addTab(images[i],clazz[i],tags[i],i,bundle);
        }

        //设置显示哪个tab
        fthMainBottonLayout.setCurrentTab(1);

    }

    private void addTab(int image, Class clazz, String tag, int i, Bundle bundle) {
        TabHost.TabSpec tabSpec = fthMainBottonLayout.newTabSpec(tag);

        View view = View.inflate(getBaseContext(), R.layout.tab_indicator, null);
        ImageView ivIcon = view.findViewById(R.id.iv_icon);
        ivIcon.setImageResource(image);

        tabSpec.setIndicator(view);
        //将Tab按钮添加进Tab选项卡中,并绑定Fragment
        fthMainBottonLayout.addTab(tabSpec,clazz,bundle);
    }

其中R.layout.tab_indicator的布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="20dp"
        android:layout_height="22dp"
        android:layout_centerHorizontal="true" />
</LinearLayout>

相关文章

网友评论

      本文标题:使用FragmentTabHost+Fragment实现底部导航

      本文链接:https://www.haomeiwen.com/subject/udhofftx.html