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的生命周期

相关文章
|
18天前
|
安全 数据处理 Android开发
构建高效Android应用:Kotlin协程的实践之路
【4月更文挑战第26天】 在面对现代Android开发时,性能优化和流畅的用户体验成为了开发者们追求的目标。Kotlin作为一种现代化的编程语言,通过其协程特性为Android应用带来了前所未有的并发处理能力。本文将深入探讨如何利用Kotlin协程提升Android应用的响应性和效率,同时保持代码的简洁性。我们将从协程的基础概念出发,逐步揭示如何在实际应用中运用这些强大的工具,以及它们如何改善应用架构和用户交互体验。
|
22天前
|
移动开发 Java Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【4月更文挑战第22天】 在移动开发领域,性能优化和响应性是衡量应用程序质量的关键指标。近年来,Kotlin语言因其简洁性和功能性在Android社区中获得了广泛认可。特别是Kotlin协程,作为一种新的并发处理机制,正在改变开发者编写异步和后台任务的方式。本文将探讨Kotlin协程的核心优势,并通过实例展示如何在Android应用中实现它们以提高性能和用户体验。
|
24天前
|
API 数据库 Android开发
构建高效Android应用:探究Kotlin协程的优化实践
【4月更文挑战第20天】 在现代Android开发中,Kotlin协程以其轻量级线程管理和非阻塞I/O操作的优势成为提升应用性能和响应性的重要工具。本文深入分析Kotlin协程的核心原理,探讨其在Android平台上实现高效并发编程的方法,并通过具体实例演示如何利用协程改进应用架构。我们将从协程的基本概念出发,逐步解析其与线程、回调和异步任务的关系,最终展示如何通过协程简化代码结构,提高运行效率,并确保用户界面的流畅性。
22 11
|
5天前
|
缓存 Java Android开发
安卓应用性能优化实践
【5月更文挑战第9天】在移动开发领域,应用的性能是决定用户体验的关键因素之一。特别是对于安卓平台,由于设备的多样性,性能优化变得尤为重要。本文将深入探讨针对安卓应用的性能优化策略,从内存管理、多线程处理到布局优化等方面提供实用的技术建议和最佳实践,帮助开发者提升应用的流畅度与响应速度。
|
14天前
|
移动开发 Java Android开发
构建高效Android应用:Kotlin协程的实践之路
【4月更文挑战第30天】在移动开发领域,随着用户需求的不断增长和设备性能的持续提升,实现流畅且高效的用户体验已成为开发者的首要任务。针对Android平台,Kotlin协程作为一种新兴的异步编程解决方案,以其轻量级线程管理和简洁的代码逻辑受到广泛关注。本文将深入探讨Kotlin协程的概念、优势以及在实际Android应用中的运用,通过实例演示如何利用协程提升应用性能和响应能力,为开发者提供一条构建更高效Android应用的实践路径。
|
1天前
|
移动开发 Android开发 开发者
构建高效Android应用:探究Kotlin协程的优化实践
【5月更文挑战第13天】 在移动开发领域,Android平台的流畅体验至关重要。随着Kotlin语言的普及,协程作为其核心特性之一,为异步编程提供了简洁且高效的解决方案。本文将深入探讨Kotlin协程在Android应用中的优化使用,从基本概念到实际案例分析,旨在帮助开发者构建更加响应迅速、性能卓越的应用。我们将通过对比传统线程与协程的差异,展示如何利用协程简化代码结构,并通过优化实践减少资源消耗,提升用户体验。
|
2天前
|
移动开发 监控 Android开发
构建高效Android应用:Kotlin协程的实践与优化
【5月更文挑战第12天】 在移动开发领域,性能与响应性是衡量一个应用程序优劣的关键指标。特别是在Android平台上,由于设备的多样性和系统资源的限制,开发者需要精心编写代码以确保应用流畅运行。近年来,Kotlin语言因其简洁性和功能性而广受欢迎,尤其是其协程特性,为异步编程提供了强大而轻量级的解决方案。本文将深入探讨如何在Android应用中使用Kotlin协程来提升性能,以及如何针对实际问题进行优化,确保应用的高效稳定执行。
|
7天前
|
调度 Android开发
Android9底部导航栏出现空白按钮问题分析
Android9底部导航栏出现空白按钮问题分析
12 0
|
8天前
|
移动开发 Java Android开发
Android应用开发:Kotlin语言的优势与实践
【5月更文挑战第7天】 在移动开发的世界中,Android平台的Kotlin语言以其高效、简洁的语法和强大的功能吸引了众多开发者。本文将深入探讨Kotlin语言的核心优势,并通过实际案例展示如何在Android应用开发中有效地运用这一现代编程语言。我们将从语言特性出发,逐步分析其在提升开发效率、改善代码质量以及增强应用性能方面的具体表现,为读者提供一个全面而细致的Kotlin应用开发指南。
|
8天前
|
Android开发
Android 底部导航的实现方式
Android 底部导航的实现方式
13 1