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设置为不可见,再次显示出来时会保存状态。


先上效果图
img_da9ae308c6596544f5db10ec6e020b70.gif
接下来就是代码咯
  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。具体情况如下图:


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

所以,在重建后的的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对象,看看销毁重建后与重建前它们是否指向同一个实例。
    img_8a311303cadad13102c24dbbc7b2b990.png

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

想看源码点击这里

如果对Activity生命周期不太了解,可以看一看我的另一篇博客:
Android笔记(一) | Activity的生命周期

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Fragment实现底部导航栏的跳转,您需要执行以下步骤: 1. 在您的项目中创建一个BottomNavigationView对象,它将用于显示底部导航栏。 2. 创建多个Fragment类,每个类都代表底部导航栏的一个选项。 3. 在您的Activity类中,创建一个FragmentManager对象并使用beginTransaction()方法开始一个新的FragmentTransaction。 4. 在FragmentTransaction中,使用add()方法将您的第一个Fragment添加到Activity中。同时,将BottomNavigationView的setOnNavigationItemSelectedListener()方法定义为一个监听器,以便在用户点击底部导航栏时执行相应的操作。 5. 在监听器中,使用replace()方法切换到用户选择的Fragment。 以下是一个简单的示例代码,可以帮助您更好地理解如何使用Fragment实现底部导航栏的跳转: ``` public class MainActivity extends AppCompatActivity { private BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottomNavigationView = findViewById(R.id.bottom_navigation); // 设置默认选中项 bottomNavigationView.setSelectedItemId(R.id.navigation_home); // 设置监听器 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment fragment; switch (menuItem.getItemId()) { case R.id.navigation_home: fragment = new HomeFragment(); break; case R.id.navigation_dashboard: fragment = new DashboardFragment(); break; case R.id.navigation_notifications: fragment = new NotificationsFragment(); break; default: return false; } getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment) .commit(); return true; } }); } } ``` 在这个例子中,我们首先获取了一个BottomNavigationView对象,并将其与我们的布局文件关联。我们还设置了默认选中项并添加了一个监听器。 在监听器中,我们使用了一个switch语句来确定用户选择了哪个选项。然后我们创建了相应的Fragment,并使用replace()方法将其添加到Activity中。 请注意,我们使用了一个FrameLayout来承载我们的Fragment。您需要在布局文件中添加一个类似的视图,以便能够动态添加和删除Fragment。 希望这可以帮助您开始使用Fragment实现底部导航栏的跳转。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值