(转)使用FragmentTabHost实现底部导航栏

原地址:http://blog.qiji.tech/archives/10406?utm_source=tuicool&utm_medium=referral


什么是 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 FragmentTabHost mTabHost;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      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 代替 TabActibvityFragment+FragmentTabHost 实现仿新浪微博底部菜单栏

其中的注意点

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

方法一:在 Fragment-onCreateView 方法中缓存 View

private View rootView;//缓存Fragment view
 
@Override  
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
    if(rootView==null){  
        rootView=inflater.inflate(R.layout.tab_fragment, null);  
    }    
    ViewGroup parent = (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 FragmentTransaction detach(Fragment fragment);

即可知道为什么会重新创建 Fragment 了: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值