Android中使用FragmentTabHost实现底部导航

什么是FragmentTabHost?

在Android较早的API中,使用导航栏一般是采用TabActibvity+TabHost+Activity,但自从Android 3.0中引入了Fragment后,上述方式则不再被官方推荐,而是推荐使用FragmentActivity+FragmentTabHost+Fragement。这样做的原因,想必大家都明白:因为Fragment比Activity更灵活,且更省资源。

因为Fragment是3.0中才引入的,Google为了保持向下兼容的风格,提供了v4包:android.support.v4.app.FragmentTabHost,如下为源码注释,想必大家一看便明白:

* Special TabHost that allows the use of {@link Fragment} objects for 
* its tab content. When placing this in a view hierarchy, after inflating 
* the hierarchy you must call {@link #setup(Context, FragmentManager, int)} 
* to complete the initialization of the tab host.

怎么使用FragmentTabHost?

对于一个知识点,网上肯定有很多文章,大家通过关键词都能搜到其使用方式,但是大家千万别忘了Google也提供了demo,这也是学习的很好方法:support/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.java:

public class FragmentTabs extends FragmentActivity {
private FragmentTabHostmTabHost;
 
@Override
protected void onCreate(BundlesavedInstanceState) {
    super.onCreate(savedInstanceState);
 
    setContentView(R.layout.fragment_tabs);
    mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
 
    mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
            FragmentStackSupport.CountingFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
            LoaderCursorSupport.CursorLoaderListFragment.class, null);
}
}
 

对应的布局文件fragment_tabs.xml如下:

<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
 
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TabWidget
        android:id="@android:id/tabs"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"/>
 
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0"/>
 
    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
 
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
 

其中有两个主要点:android:id/tabhost和@+id/realtabcontent,前者为系统定义的TabHost导航条,后者为主体内容(即Tab点击时,加载Fragment区域),通过使用mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent)将两者结合起来。具体的使用方式,大家可以参照: 使用FragmentTabhost代替TabActibvity 、 Fragment+FragmentTabHost实现仿新浪微博底部菜单栏

其中的注意点

demo运行起来后发现,当从tabA切换到tabB,然后再次切换到tabA时,发现对应的Fragment会重新加载,重新创建布局。这样会引起一个问题:如果布局里有较多的View,则每次tab项切换时重新创建布局会很浪费时间,并且重新创建后,也保存不了之前的状态。对此,网上也有些解决办法:

方法一:在Fragment-onCreateView方法中缓存View
private ViewrootView;//缓存Fragment view
 
@Override  
public ViewonCreateView(LayoutInflaterinflater, ViewGroupcontainer, BundlesavedInstanceState) {  
    if(rootView==null){  
        rootView=inflater.inflate(R.layout.tab_fragment, null);  
    }    
    ViewGroupparent = (ViewGroup) rootView.getParent();  
    if (parent != null) {  
        parent.removeView(rootView);  
    }  
    return rootView;  
}
 

这种办法会复用之前的View,但是如果在Fragment界面还有数据请求调用的话,比如在onActivityCreated(Bundle savedInstanceState)方法里面还有数据请求的话,它也会重新被调用,如果不希望重新调用,可以采用方法二.

方法二:自定义FragmentTabHost,使用hide()和show()替换detach()和attach()

通过查看FragmentTabHost的源码发现,tab项在切换时,FragmentTransaction是使用detach()来移除fragment的,仔细看该方法:

/**
* Detach the given fragment from the UI.  This is the same state as
* when it is put on the back stack: the fragment is removed from
* the UI, however its state is still being actively managed by the
* fragment manager.  When going into this state its view hierarchy
* is destroyed.
*
* @param fragment The fragment to be detached.
*
* @return Returns the same FragmentTransaction instance.
*/
 
public abstract FragmentTransactiondetach(Fragmentfragment);
 

即可知道为什么会重新创建fragmet了: When going into this state its view hierarchy is destroyed. 。既然知道原理了,我们可以自定义FragmentTabHost,将其中的detach()和attach()替换为hide()和show()。通过动手,我们发现切换tab时,fragment不会再重新创建,达到目的,YES!

总结

这是实现Tab导航的一种方式。当然随着Android Material Design的推出,还有些新的方式实现导航栏: BottomNavigationBar 浅析 ,大家可以学习下。

另外推荐文章: TabHost 和 FragmentTabHost

第一篇Android的文章,如有问题请指出,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现底部导航栏,可以使用 Android TabLayout 和 ViewPager。具体步骤如下: 1. 在布局文件添加 TabLayout 和 ViewPager 组件。 2. 创建三个 Fragment,并在每个 Fragment 添加相应的布局和逻辑。 3. 创建一个 PagerAdapter,用于将 FragmentTabLayout 绑定。 4. 在 MainActivity 设置 ViewPager 的适配器,并将 TabLayout 和 ViewPager 进行绑定。 5. 在 MainActivity 添加底部导航栏的选项卡,并设置选项卡的图标和标签。 6. 在 MainActivity 添加选项卡的点击事件,以便切换不同的 Fragment。 下面是一个简单的实现示例: MainActivity.java: ```java public class MainActivity extends AppCompatActivity { private TabLayout mTabLayout; private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTabLayout = findViewById(R.id.tab_layout); mViewPager = findViewById(R.id.view_pager); // 创建三个 Fragment Fragment1 fragment1 = new Fragment1(); Fragment2 fragment2 = new Fragment2(); Fragment3 fragment3 = new Fragment3(); // 创建 PagerAdapter MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager()); adapter.addFragment(fragment1, "Tab 1"); adapter.addFragment(fragment2, "Tab 2"); adapter.addFragment(fragment3, "Tab 3"); // 设置 ViewPager 的适配器 mViewPager.setAdapter(adapter); // 将 TabLayout 和 ViewPager 进行绑定 mTabLayout.setupWithViewPager(mViewPager); // 设置选项卡的图标和标签 mTabLayout.getTabAt(0).setIcon(R.drawable.ic_tab1).setText("Tab 1"); mTabLayout.getTabAt(1).setIcon(R.drawable.ic_tab2).setText("Tab 2"); mTabLayout.getTabAt(2).setIcon(R.drawable.ic_tab3).setText("Tab 3"); // 添加选项卡的点击事件,以便切换不同的 Fragment mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } // 自定义 PagerAdapter private class MyPagerAdapter extends FragmentPagerAdapter { private List<Fragment> mFragmentList = new ArrayList<>(); private List<String> mTitleList = new ArrayList<>(); public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mTitleList.add(title); } @Nullable @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } } } ``` activity_main.xml: ```xml <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" app:tabGravity="fill" app:tabIndicatorColor="@android:color/white" app:tabIndicatorHeight="2dp" app:tabSelectedTextColor="@android:color/white" app:tabTextColor="@android:color/white" /> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> ``` 注意:上述代码使用Android Support Library,如果你使用的是 AndroidX 的话,需要将相应的组件和包名进行更改。另外,还需要在 build.gradle 文件添加相应的依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值