阅读 292

Android实践 | Fragment实现底部导航栏(彻底解决重叠问题)

回顾最初学习Android的时候,是边学习边做着一个小项目的,因为项目需求,需要实现一个底部导航栏的功能,由于基础知识受限,百度了很多博客,大致就找到两种实现方案:

  • 第一种就是直接用Fragment实现(点击切换)

  • 第二种是ViewPager+Fragment实现(除了点击切换,还支持左右滑动切换)。

然后根据需求使用了第一种方法,后期产生了Fragment重叠的问题,由于这个bug时而出现,也不知道如何定位(学生时期),就暂且放下了。现在因为学习进度(系统学习Fragment),重新捡起这个问题,就想写一篇实现功能+解决bug的博客,如有不足之处,请留言指教。

实现思路

当我们进入Activity时,首先展示第一个页面,即创建对应Fragment实例,使用add+show方法显示出来,当我们点击进入别的页面时,调用hide方法将已展示的Fragment页面隐藏(实际是设置Visiable属性为不可见),然后显示对应Fragment页面(已创建则直接调用show方法,未创建则创建,然后调用add+show方法显示)。


这里补充一点:切换页面也可以用replace方法,它和hide+show方法的直观区别就是:使用replace方法会先将fragment实例remove掉,然后重新add,这就导致Fragment每次切换都会重新走一遍生命周期,创建一个新的实例,不会保存每个Fragment的状态;而使用hide+show方法则仅仅是将不显示的Fragment设置为不可见,再次显示出来时会保存状态。


先上效果图

image

接下来就是代码咯
  1. 首先创建一个Activity,写好页面布局。

  • 首先新建一个Layout Xml File bottombar.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@color/colorBackGround"     android:paddingTop="5dp"     android:paddingBottom="5dp">     <TextView         android:id="@+id/text_clothes"         android:layout_width="0dp"         android:layout_weight="1"         android:layout_height="wrap_content"         android:drawableTop="@drawable/ic_clothes"         android:text="@string/clothes"         android:textSize="13sp"         android:gravity="center_horizontal"/>     <TextView         android:id="@+id/text_food"         android:layout_width="0dp"         android:layout_weight="1"         android:layout_height="wrap_content"         android:drawableTop="@drawable/ic_food"         android:text="@string/food"         android:textSize="13sp"         android:gravity="center_horizontal"/>     <TextView         android:id="@+id/text_hotel"         android:layout_width="0dp"         android:layout_weight="1"         android:layout_height="wrap_content"         android:drawableTop="@drawable/ic_hotel"         android:text="@string/hotel"         android:textSize="13sp"         android:gravity="center_horizontal"/> </LinearLayout> 复制代码

  • activity_main.xml中使用include标签引用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context=".MainActivity">     <FrameLayout         android:id="@+id/container"         android:layout_width="match_parent"         android:layout_height="0dp"         android:layout_weight="1"/>     <View         android:background="@color/colorGray"         android:layout_width="match_parent"         android:layout_height="0.1dp"/>     <include layout="@layout/bottombar"/> </LinearLayout> 复制代码

  1. 布局写好了,接下来新建三个空白Fragment(这里只列出一个)

  • ClothesFragment.java

import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.laughter.testdemo.R; /**  * A simple {@link Fragment} subclass.  */ public class ClothesFragment extends Fragment {     public ClothesFragment() {         // Required empty public constructor     }     @Override     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.fragment_clothes, container, false);     } } 复制代码

  • fragment_clothes.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".fragment.ClothesFragment">     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:text="@string/clothes"         android:textSize="72sp"         android:gravity="center"/> </FrameLayout> 复制代码

我这里为了区分Fragment页面给每个页面添加了一个TextView,具体就根据自己的需求在Fragment中写代码就行了。

  1. 接下来就是在MainActivity中写逻辑控制Fragment的切换了。

import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.example.laughter.testdemo.fragment.ClothesFragment; import com.example.laughter.testdemo.fragment.FoodFragment; import com.example.laughter.testdemo.fragment.HotelFragment; public class MainActivity extends AppCompatActivity implements View.OnClickListener{     //底部菜单栏3个TextView     private TextView mTextClothes;     private TextView mTextFood;     private TextView mTextHotel;     //3个Fragment     private Fragment mClothesFragment;     private Fragment mFoodFragment;     private Fragment mHotelFragment;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         //初始化         init();         //设置第一个Fragment默认显示         setFragment(0);     }     @Override     public void onClick(View v) {         switch (v.getId()){             default:                 break;             case R.id.text_clothes:                 setFragment(0);                 break;             case R.id.text_food:                 setFragment(1);                 break;             case R.id.text_hotel:                 setFragment(2);                 break;         }     }     private void init(){         //初始化控件         mTextClothes = (TextView)findViewById(R.id.text_clothes);         mTextFood = (TextView)findViewById(R.id.text_food);         mTextHotel = (TextView)findViewById(R.id.text_hotel);         //设置监听         mTextClothes.setOnClickListener(this);         mTextFood.setOnClickListener(this);         mTextHotel.setOnClickListener(this);     }     private void setFragment(int index){         //获取Fragment管理器         FragmentManager mFragmentManager = getSupportFragmentManager();         //开启事务         FragmentTransaction mTransaction = mFragmentManager.beginTransaction();         //隐藏所有Fragment         hideFragments(mTransaction);         switch (index){             default:                 break;             case 0:                 //设置菜单栏为选中状态(修改文字和图片颜色)                 mTextClothes.setTextColor(getResources()                         .getColor(R.color.colorTextPressed));                 mTextClothes.setCompoundDrawablesWithIntrinsicBounds(0,                         R.drawable.ic_clothes_pressed,0,0);                 //显示对应Fragment                 if(mClothesFragment == null){                     mClothesFragment = new ClothesFragment();                     mTransaction.add(R.id.container, mClothesFragment,                             "clothes_fragment");                 }else {                     mTransaction.show(mClothesFragment);                 }                 break;             case 1:                 mTextFood.setTextColor(getResources()                         .getColor(R.color.colorTextPressed));                 mTextFood.setCompoundDrawablesWithIntrinsicBounds(0,                         R.drawable.ic_food_pressed,0,0);                 if(mFoodFragment == null){                     mFoodFragment = new FoodFragment();                     mTransaction.add(R.id.container, mFoodFragment,                             "food_fragment");                 }else {                     mTransaction.show(mFoodFragment);                 }                 break;             case 2:                 mTextHotel.setTextColor(getResources()                         .getColor(R.color.colorTextPressed));                 mTextHotel.setCompoundDrawablesWithIntrinsicBounds(0,                         R.drawable.ic_hotel_pressed,0,0);                 if(mHotelFragment == null){                     mHotelFragment = new HotelFragment();                     mTransaction.add(R.id.container, mHotelFragment,                             "hotel_fragment");                 }else {                     mTransaction.show(mHotelFragment);                 }                 break;         }         //提交事务         mTransaction.commit();     }     private void hideFragments(FragmentTransaction transaction){         if(mClothesFragment != null){             //隐藏Fragment             transaction.hide(mClothesFragment);             //将对应菜单栏设置为默认状态             mTextClothes.setTextColor(getResources()                     .getColor(R.color.colorText));             mTextClothes.setCompoundDrawablesWithIntrinsicBounds(0,                     R.drawable.ic_clothes,0,0);         }         if(mFoodFragment != null){             transaction.hide(mFoodFragment);             mTextFood.setTextColor(getResources()                     .getColor(R.color.colorText));             mTextFood.setCompoundDrawablesWithIntrinsicBounds(0,                     R.drawable.ic_food,0,0);         }         if(mHotelFragment != null){             transaction.hide(mHotelFragment);             mTextHotel.setTextColor(getResources()                     .getColor(R.color.colorText));             mTextHotel.setCompoundDrawablesWithIntrinsicBounds(0,                     R.drawable.ic_hotel,0,0);         }     } } 复制代码

上面代码中逻辑很清晰,根据注释基本可以看明白,具体有些控件的用法自行百度。到这里功能就已经实现了,但是会出现Fragment重叠的bug。具体情况如下图:

image

  1. 出现这种情况是什么原因呢?了解Activity的生命周期的话,你就知道默认情况下,当我们旋转屏幕时,Activity会销毁重建,这个过程属于异常情况下的生命周期,系统会调用onSaveInstanceState和onRestoreInstanceState方法保存并恢复Activity的状态,而Fragment也在恢复的内容之中。但是在之前的Activity中我们创建了Fragment的实例,并且add到FragmentTransaction中了,这些实例在Activity重建时并没有remove,只不过Activity重建之后,没有对象指向它们,也就是说,在重建后的Activity中,我们创建的3个fragmeng对象是指向null的。

    image

所以,在重建后的的Activity中,又会重新创建Fragment的实例,并且显示出来,而之前被系统恢复的Fragment也会恢复之前的显示状态,这就导致了多个Fragment重叠。当然,任何能导致Activity销毁重建的情况都会产生这个bug,比如说应用在后台时,因为内存资源不足导致Activity被kill。既然知道原因了,那么解决起来就不难了。 这里我想到的解决办法是从重新创建Fragment这里着手,既然保存的状态会恢复,那么Activity重建的时候我们不让Fragment重新创建不就行了。具体怎么做呢?这里还是需要熟悉Activity的生命周期。

  • 首先,我们要在onCreate方法中添加一个判断,当Activity不是异常终止并恢复(即savedInstanceState == null)时,才显示默认Fragment。

    @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         //初始化         init();         //根据传入的Bundle对象判断Activity是正常启动还是销毁重建         if(savedInstanceState == null){             //设置第一个Fragment默认选中             setFragment(0);         }     } 复制代码

  • 然后,我们要获取到原本已经创建的Fragmen实例,并让重建后的Activity中的Fragment对象指向它们。并且设置一个变量,用于保存在销毁重建前显示的是哪个Fragment。这两个操作需要重写onSaveInstanceState方法和onRestoreInstanceState方法。(这里只贴出修改过的代码)

public class MainActivity extends AppCompatActivity implements View.OnClickListener{     ...     //标记当前显示的Fragment     private int fragmentId = 0;     ...     @Override     protected void onSaveInstanceState(Bundle outState) {         //通过onSaveInstanceState方法保存当前显示的fragment         outState.putInt("fragment_id",fragmentId);         super.onSaveInstanceState(outState);     }     @Override     protected void onRestoreInstanceState(Bundle savedInstanceState) {         super.onRestoreInstanceState(savedInstanceState);         FragmentManager mFragmentManager = getSupportFragmentManager();         //通过FragmentManager获取保存在FragmentTransaction中的Fragment实例         mClothesFragment = (ClothesFragment)mFragmentManager                 .findFragmentByTag("clothes_fragment");         mFoodFragment = (FoodFragment)mFragmentManager                 .findFragmentByTag("food_fragment");         mHotelFragment = (HotelFragment)mFragmentManager                 .findFragmentByTag("hotel_fragment");         //恢复销毁前显示的Fragment         setFragment(savedInstanceState.getInt("fragment_id"));     }     ...     复制代码

  • 修改之后,我们可以打印出Fragment对象,看看销毁重建后与重建前它们是否指向同一个实例。

    image

显然,销毁重建后Fragment对象所指向的实例与重建前相同。这样我们的BottomBar就完成了!


作者:Coolbreeze
链接:https://juejin.cn/post/7018896498716835870


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐