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

简介: 最初学习Android的时候,是边学习边做着一个小项目的,因为项目需求,需要实现一个底部导航栏的功能,由于基础知识受限,百度了很多博客,大致就找到两种实现方案:第一种就是直接用Fragment实现(点击切换),第二种是ViewPager+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的生命周期

相关文章
|
16天前
|
移动开发 安全 Android开发
构建高效Android应用:Kotlin协程的实践与优化策略
【5月更文挑战第30天】 在移动开发领域,性能优化始终是关键议题之一。特别是对于Android开发者来说,如何在保证应用流畅性的同时,提升代码的执行效率,已成为不断探索的主题。近年来,Kotlin语言凭借其简洁、安全和实用的特性,在Android开发中得到了广泛的应用。其中,Kotlin协程作为一种新的并发处理机制,为编写异步、非阻塞性的代码提供了强大工具。本文将深入探讨Kotlin协程在Android开发中的应用实践,以及如何通过协程优化应用性能,帮助开发者构建更高效的Android应用。
|
29天前
|
移动开发 API Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第17天】在移动开发领域,性能优化和流畅的用户体验一直是开发者追求的目标。针对Android平台,Kotlin语言凭借其简洁性和功能丰富性成为了许多开发者的首选。其中,Kotlin协程作为异步编程的强大工具,为处理并发任务提供了轻量级的解决方案。本文深入探讨了Kotlin协程的核心优势,并通过实例分析其在Android开发中的应用,旨在帮助开发者提升应用的性能和响应能力。
|
16天前
|
物联网 区块链 Android开发
构建高效Android应用:Kotlin与Jetpack的实践之路未来技术的融合潮流:区块链、物联网与虚拟现实的交汇点
【5月更文挑战第30天】 在移动开发领域,效率和性能始终是开发者追求的核心。随着技术的不断进步,Kotlin语言以其简洁性和现代化特性成为Android开发的新宠。与此同时,Jetpack组件为应用开发提供了一套经过实践检验的库、工具和指南,旨在简化复杂任务并帮助提高应用质量。本文将深入探索如何通过Kotlin结合Jetpack组件来构建一个既高效又稳定的Android应用,并分享在此过程中的最佳实践和常见陷阱。
|
17天前
|
运维 监控 Android开发
构建高效自动化运维系统的策略与实践构建高效Android应用:Kotlin协程的实践指南
【5月更文挑战第29天】随着信息技术的迅猛发展,企业IT基础设施变得日益复杂,传统的手动运维模式已难以满足高效率、高稳定性的要求。本文将深入探讨如何通过自动化工具和策略来构建一个高效的自动化运维系统。文中不仅分析了自动化运维的必要性,还详细介绍了实现过程中的关键步骤,包括监控、配置管理、故障响应等,并结合实际案例分析其效果,以期为读者提供一套行之有效的自动化运维解决方案。
|
17天前
|
移动开发 数据库 Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第29天】 随着移动开发技术的不断进步,开发者寻求更高效、更简洁的方式来编写代码。在Android平台上,Kotlin语言凭借其现代化的特性和对协程的原生支持,成为提高开发效率的关键。本文将深入分析Kotlin协程的核心优势,并通过实例展示如何在Android应用开发中有效地利用协程来处理异步任务,优化性能,以及提升用户体验。通过对比传统线程和回调机制,我们将揭示协程如何简化异步编程模型,并减少内存消耗,使应用更加健壮和可维护。
|
19天前
|
移动开发 安全 编译器
构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第27天】 在移动开发领域,性能优化和流畅的用户体验始终是开发者追求的目标。随着Android对Kotlin的支持日益增强,Kotlin协程作为一种新的并发处理方式,为Android应用的性能提升提供了新的可能性。本文将深入探讨Kotlin协程的核心优势,并通过具体实例展示如何在Android应用中有效利用协程来提升响应速度、减少内存消耗,并简化异步代码。
|
19天前
|
存储 缓存 算法
深入理解操作系统内存管理:分页系统的优势与挑战构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第27天】 在现代计算机系统中,内存管理是操作系统的核心功能之一。分页系统作为一种内存管理技术,通过将物理内存划分为固定大小的单元——页面,为每个运行的程序提供独立的虚拟地址空间。这种机制不仅提高了内存的使用效率,还为多任务环境提供了必要的隔离性。然而,分页系统的实现也带来了一系列的挑战,包括页面置换算法的选择、内存抖动问题以及TLB(Translation Lookaside Buffer)的管理等。本文旨在探讨分页系统的原理、优势及其面临的挑战,并通过分析现有解决方案,提出可能的改进措施。
|
19天前
|
缓存 移动开发 Android开发
安卓应用性能优化实践
【5月更文挑战第27天】在移动开发领域,应用的性能直接影响用户体验。特别是对于安卓平台,由于设备多样性和应用生态环境的复杂性,性能优化成为了开发者的一项重要任务。本文将探讨针对安卓平台进行应用性能优化的策略与实践,包括内存管理、电池效率以及响应速度提升等方面,旨在为开发人员提供一套实用的性能调优工具和思路。
|
19天前
|
数据库 Android开发 UED
构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第27天】 在面对移动应用开发时,性能优化和异步处理是提升用户体验的关键。Android平台上,Kotlin语言凭借其简洁性和功能性成为开发的首选之一。特别是Kotlin协程的引入,为开发者提供了一种更加简洁、高效的方式来处理并发和后台任务。本文将深入探讨Kotlin协程的核心原理,展示其在Android开发中的应用优势,并通过实例代码演示如何在实际项目中有效利用协程来改善应用性能和响应速度。
|
19天前
|
移动开发 调度 Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【5月更文挑战第27天】随着移动开发技术的不断进步,开发者寻求更高效、简洁的编码方式以提升应用性能和用户体验。Kotlin作为一种现代编程语言,在Android开发中逐渐占据重要地位,特别是其协程功能为异步编程带来了革命性的改进。本文将深入探讨Kotlin协程的核心优势,并通过实际案例演示如何在Android应用中有效利用协程来优化性能和简化代码结构。