美文网首页
FragmentTabHost实现Toolbar+viewpag

FragmentTabHost实现Toolbar+viewpag

作者: it奔跑在路上 | 来源:发表于2019-04-24 17:26 被阅读0次

FragmentTabHost实现底部Tab切换的效果,效果图如下:

GIF.gif

下载链接:https://share.weiyun.com/5ctPWmv

FragmentTabHost来自于android.support.v4.app这个包下,继承自TabHost,因此:

需要注意:FragmentTabHost、TabWidget、FrameLayout的id必须是使用 android:id/XXX,不能使用自定义的id即 +id/ 。

public class MainActivity extends AppCompatActivity{

    private String[] tabNameArray = {"页面1", "页面2"};
    private Class[] fragments = {DemoFragment.class, Demo2Fragment.class};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        FragmentTabHost tabHost = (FragmentTabHost) findViewById(R.id.fth_main);
        int[] rID = new int[]{R.drawable.selector_tab_home, R.drawable.selector_tab_me};
        tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        tabHost.getTabWidget().setDividerDrawable(null);
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < tabNameArray.length; i++) {
            View view = inflater.inflate(R.layout.layout_tabview, null);
            ImageView tabicon = view.findViewById(R.id.iv_tab_icon);
            TextView tabName = view.findViewById(R.id.tv_tab_name);
            tabicon.setImageResource(rID[i]);
            tabName.setText(this.tabNameArray[i]);
            tabHost.addTab(tabHost.newTabSpec(tabNameArray[i]).setIndicator(view), fragments[i], null);
        }
    }
}
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fth_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:orientation="horizontal" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:orientation="horizontal" />
    </LinearLayout>
</android.support.v4.app.FragmentTabHost>

如果你想自定义,可以参考《 自定义通用的底部导航栏(四)》

相关文章

网友评论

      本文标题:FragmentTabHost实现Toolbar+viewpag

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