Android进阶之路 - 通过 BottomNavigationView + FrameLayout 实现底部导航栏

2020年都过半了,回头一看当年我竟然如此厉害,着实佩服自己 < .<

Fragment基础Blog

项目之初,我们都需要搭建UI界面,而底部导航的承载效果是不可或缺的,在我认知中主要有以下几种实现方式

  • Tablayout + ViewPager + Fragment
  • LinearLayout + TextView + ImageView
  • RadioGroup + RadioButton
  • BottomNavigationView + FrameLayout

对于一个项目,底部导航基本是标配,特提供我自己记录的几篇Blog

基础认知

在app的现有市场,主页面UI框架基本都兼容多个Fragment,关于主页的常见布局框架结构,在我的认知中主要有以下几种(排名无先后,具体看场景

  • TabLayout + ViewPager支持滑动,点击
  • BottomNavigationView + ViewPager支持滑动,点击
  • BottomNavigationView + FrameLayout仅支持点击
  • LinearLayout + FrameLayout仅支持点击
  • RadioGroup、RadioButton仅支持点击

关于这种布局涉及Tab切换操作也很频繁,所以有必要了解一下Fragment的俩种切换方式

  1. replace方式 - 基本每次replace都会创建一次Fragment实例,其实很少用

关键API

 transaction.replace(R.id.fragnment, fragment1);
  1. add-hide-show方式 - 开发中教常用的一种方式,减少了不必要的开销

关键API

 transaction.add(R.id.fragnment, fragment1); 
 transaction.hide(fragment1); 
 transaction.show(fragment2);

Fragment切换 (2017)

replace 方式 - Java

布局方式:LinearLayout + FrameLayout

实现效果(当年不会git图)

Demo结构图

代码实践 - Java

废话不多讲,代码奉上:

package com.example.fragment;

import com.example.fragment.R;
import com.example.fragment.R.color;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private TextView m1;
	private TextView m2;
	private TextView m3;
	private TextView m4;
	private View v4;
	private View v2;
	private View v1;
	private View v3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();
		initState();
		initEvent();
	}
	
	private void initView() {
		m1 = (TextView) findViewById(R.id.t1);
		m2 = (TextView) findViewById(R.id.t2);
		m3 = (TextView) findViewById(R.id.t3);
		m4 = (TextView) findViewById(R.id.t4);
		v1 = findViewById(R.id.v1);
		v2 = findViewById(R.id.v2);
		v3 = findViewById(R.id.v3);
		v4 = findViewById(R.id.v4);
	}

	private void initState() {
		// 初始化
		FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
				new Fragment1());
		v1.setBackgroundColor(Color.RED);
		m1.setTextColor(Color.RED);
	}

	private void initEvent() {
		m1.setOnClickListener(this);
		m2.setOnClickListener(this);
		m3.setOnClickListener(this);
		m4.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.t1:
			FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
					new Fragment1());
			checkState(1);
			break;
		case R.id.t2:
			FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
					new Fragment2());
			checkState(2);
			break;
		case R.id.t3:
			FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
					new Fragment3());
			checkState(3);
			break;
		case R.id.t4:
			FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
					new Fragment4());
			checkState(4);
			break;
		default:
			break;
		}
	}

	//为了不破坏当年的代码思想,2021年的时候简单抽了一下之前的代码...
    public void checkState(int index) {
        v1.setBackgroundColor(color.huise);
        v2.setBackgroundColor(color.huise);
        v3.setBackgroundColor(color.huise);
        v4.setBackgroundColor(color.huise);
        m1.setTextColor(Color.BLACK);
        m2.setTextColor(Color.BLACK);
        m3.setTextColor(Color.BLACK);
        m4.setTextColor(Color.BLACK);

        if (index == 1) {
            v1.setBackgroundColor(Color.RED);
            m1.setTextColor(Color.RED);
            return;
        }
        if (index == 2) {
            v2.setBackgroundColor(Color.RED);
            m2.setTextColor(Color.RED);
            return;
        }
        if (index == 3) {
            v3.setBackgroundColor(Color.RED);
            m3.setTextColor(Color.RED);
            return;
        }
        if (index == 4) {
            v4.setBackgroundColor(Color.RED);
            m4.setTextColor(Color.RED);
        }
    }
}

Tab切换时状态变更(自己写的颜色,可根据结构图,查看其的位置)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#26262626"/>
</selector>

子 Fragment 示例

package com.example.fragment;

import com.example.fragment.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.f1, null);
		return view;
	}
}

activity_main

<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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/t1"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:gravity="center"
            android:text="全部"
            android:textSize="11sp" />

        <TextView
            android:layout_width="0dp"
            android:id="@+id/t2"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="正在进行"
            android:textSize="11sp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:id="@+id/t3"
            android:gravity="center"
            android:text="即将开始"
            android:textSize="11sp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:id="@+id/t4"
            android:gravity="center"
            android:text="已经售完"
            android:textSize="11sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:orientation="horizontal" >

        <View
            android:id="@+id/v1"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:background="#26262626" />

        <View
            android:id="@+id/v2"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:background="#26262626" />

        <View
            android:id="@+id/v3"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:background="#26262626" />

        <View
            android:id="@+id/v4"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:background="#26262626" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fl_Demo"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

</LinearLayout>

Fragment 切换 (2022)

replace 方式 - Kt

伪代码:忽略框架部分,只看Fragment相关部分

package com.jsmedia.jsmanager.basic

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ToastUtils
import com.eyepetizer.android.event.GameEvent
import com.eyepetizer.android.event.MessageEvent
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ktx.immersionBar
import com.jsmedia.jsmanager.R
import com.jsmedia.jsmanager.activity.publish.PublishCreateActivity
import com.jsmedia.jsmanager.base.BaseVMActivity
import com.jsmedia.jsmanager.base.BaseViewModel
import com.jsmedia.jsmanager.bean.IMSigBean
import com.jsmedia.jsmanager.databinding.ActivityMainBinding
import com.jsmedia.jsmanager.event.HomeMsgEvent
import com.jsmedia.jsmanager.event.InvalidTokenEvent
import com.jsmedia.jsmanager.event.LogoutTokenEvent
import com.jsmedia.jsmanager.fragment.game.GameFragment
import com.jsmedia.jsmanager.fragment.mine.MineFragment
import com.jsmedia.jsmanager.fragment.msg.MsgFragment
import com.jsmedia.jsmanager.home.fragment.HomeFragment
import com.jsmedia.jsmanager.imMessage.CustomMessageFragment
import com.jsmedia.jsmanager.imMessage.IMViewModel
import com.jsmedia.jsmanager.third.tim.push.TUIOfflinePushService
import com.jsmedia.jsmanager.utils.DataStoreUtil
import com.jsmedia.jsmanager.utils.DynamicPublishUtil
import com.jsmedia.jsmanager.utils.LyUtil
import com.jsmedia.jsmanager.utils.TUIUtils
import com.jsmedia.jsmanager.view.sweetdialog.StatueLayout
import com.tencent.imsdk.v2.*
import com.tencent.mmkv.MMKV
import com.ypx.imagepicker.bean.ImageItem
import com.ypx.imagepicker.bean.PickerError
import com.ypx.imagepicker.data.OnImagePickCompleteListener2
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

class MainActivity : BaseVMActivity<ActivityMainBinding, BaseViewModel>() {

    override fun setStatueLayout(): StatueLayout? = null
    override fun isNormalStatus() = false
    private val imViewModel by viewModel<IMViewModel>()

    @SuppressLint("ResourceType")
    override fun initView() {
        binding.run { vm = imViewModel }
        
        //获取底部导航图标颜色,根据图标颜色设置文字颜色
        val csl: ColorStateList = resources.getColorStateList(R.drawable.bottom_text_selected)
        binding.bn.itemTextColor = csl
        binding.bn.itemIconTintList = null;
        setDefaultFragment()
        isTrans(false)
        binding.bn.itemIconTintList = null;

        binding.bn.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.item_tab1 -> {
                    replaceFragment(HomeFragment(), R.id.fl)
                    Log.e("1", "1")
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab2 -> {
                    replaceFragment(GameFragment(), R.id.fl)
                    Log.e("2", "2")
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab3 -> {
                    Log.e("3", "3")
                    publishPhoto()
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab4 -> {
                    replaceFragment(MsgFragment(), R.id.fl)
                    Log.e("4", "4")
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab5 -> {
                    replaceFragment(MineFragment(), R.id.fl)
                    Log.e("5", "5")
                    return@OnNavigationItemSelectedListener true
                }
            }
            false
        })
    }

	/**
	* 状态栏设定,可忽略
	*/
    fun isTrans(isTrans: Boolean) {
        if (isTrans) {
            immersionBar {
                transparentStatusBar()
                navigationBarColor(R.color.gray)
                statusBarDarkFont(true)
            }
        } else {
            immersionBar {
                // fitsSystemWindows(true)
                statusBarColor(R.color.white)
                navigationBarColor(R.color.gray)
                autoDarkModeEnable(true)
            }
        }
    }

    // 设置默认进来时 tab 显示的页面
    fun setDefaultFragment() {
        val supportFragmentManager = supportFragmentManager
        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.replace(R.id.fl, HomeFragment())
        beginTransaction.commit()
    }

    inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
        beginTransaction().func().commit()
    }

    fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int) {
        supportFragmentManager.inTransaction { add(frameId, fragment) }
    }

    fun AppCompatActivity.replaceFragment(fragment: Fragment, frameId: Int) {
        supportFragmentManager.inTransaction { replace(frameId, fragment) }
        isTrans(fragment is GameFragment)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        //关闭程序
        finishAffinity()
    }

activity_main

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="vm"
            type="com.jsmedia.jsmanager.imMessage.IMViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".basic.MainActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <FrameLayout
                android:id="@+id/fl"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />

            <com.google.android.material.bottomnavigation.BottomNavigationView
                android:id="@+id/bn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#e4e4e4"
                app:itemTextColor="@drawable/bottom_text_selected"
                app:labelVisibilityMode="labeled"
                app:menu="@menu/bottom_menu" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

            <ImageView
                android:layout_width="@dimen/dp_40"
                android:layout_height="@dimen/dp_40"
                android:layout_marginBottom="@dimen/dp_5"
                android:src="@mipmap/ic_s_publish" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginBottom="@dimen/dp_5"
                android:text="发布"
                android:textColor="@color/black_def"
                android:textSize="@dimen/dp_12" />

        </LinearLayout>

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="54dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent">

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <FrameLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView
                    android:id="@+id/tv_remindMsgNum"
                    android:layout_width="@dimen/dp_10"
                    android:layout_height="@dimen/dp_10"
                    android:layout_gravity="right"
                    android:layout_marginTop="@dimen/dp_4"
                    android:background="@drawable/shape_red_dot"
                    android:gravity="center"
                    android:textColor="@color/white"
                    android:textSize="@dimen/sp_10"
                    android:visibility="gone"
                    app:layout_constraintCircle="@id/tv_tab_title"
                    app:layout_constraintCircleAngle="60"
                    app:layout_constraintCircleRadius="@dimen/dp_25"
                    tools:visibility="visible" />

                <TextView
                    android:id="@+id/tv_hdMsgNum"
                    android:layout_width="@dimen/dp_18"
                    android:layout_height="@dimen/dp_18"
                    android:layout_gravity="right"
                    android:layout_marginTop="@dimen/dp_2"
                    android:background="@drawable/shape_red_dot"
                    android:gravity="center"
                    android:text="1"
                    android:textColor="@color/white"
                    android:textSize="12sp"
                    android:visibility="gone"
                    app:layout_constraintCircle="@id/tv_tab_title"
                    app:layout_constraintCircleAngle="60"
                    app:layout_constraintCircleRadius="@dimen/dp_25"
                    tools:text="99"
                    tools:visibility="visible" />
            </FrameLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />
        </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
hind、show 方式 - Kt

xml 布局同上方,不在赘述

package com.jsmedia.jsmanager.basic

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ToastUtils
import com.eyepetizer.android.event.GameEvent
import com.eyepetizer.android.event.MessageEvent
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ktx.immersionBar
import com.jsmedia.jsmanager.R
import com.jsmedia.jsmanager.activity.publish.PublishCreateActivity
import com.jsmedia.jsmanager.base.BaseVMActivity
import com.jsmedia.jsmanager.base.BaseViewModel
import com.jsmedia.jsmanager.bean.IMSigBean
import com.jsmedia.jsmanager.databinding.ActivityMainBinding
import com.jsmedia.jsmanager.event.*
import com.jsmedia.jsmanager.fragment.game.GameFragment
import com.jsmedia.jsmanager.fragment.mine.MineFragment
import com.jsmedia.jsmanager.fragment.msg.MsgFragment
import com.jsmedia.jsmanager.home.fragment.HomeFragment
import com.jsmedia.jsmanager.imMessage.CustomMessageFragment
import com.jsmedia.jsmanager.imMessage.IMViewModel
import com.jsmedia.jsmanager.third.tim.push.TUIOfflinePushService
import com.jsmedia.jsmanager.utils.*
import com.jsmedia.jsmanager.view.sweetdialog.StatueLayout
import com.tencent.imsdk.v2.*
import com.tencent.mmkv.MMKV
import com.ypx.imagepicker.bean.ImageItem
import com.ypx.imagepicker.bean.PickerError
import com.ypx.imagepicker.data.OnImagePickCompleteListener2
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

class MainActivity : BaseVMActivity<ActivityMainBinding, BaseViewModel>() {

    override fun setStatueLayout(): StatueLayout? = null
    override fun isNormalStatus() = false
    private val imViewModel by viewModel<IMViewModel>()
    var fragmentList: ArrayList<Fragment> = ArrayList<Fragment>()
    var homeFragment = HomeFragment()
    var gameFragment = GameFragment()
    var msgFragment = MsgFragment()
    var mineFragment = MineFragment()

    @SuppressLint("ResourceType")
    override fun initView() {
        binding.run { vm = imViewModel }

        //获取底部导航图标颜色,根据图标颜色设置文字颜色
        val csl: ColorStateList = resources.getColorStateList(R.drawable.bottom_text_selected)
        binding.bn.itemTextColor = csl
        binding.bn.itemIconTintList = null;
        // 设置默认进来时 tab 显示的页面
        FragmentUtils.show(this, R.id.fl, homeFragment)    
        isTrans(false)
        binding.bn.itemIconTintList = null;

        fragmentList.add(homeFragment)
        fragmentList.add(gameFragment)
        fragmentList.add(msgFragment)
        fragmentList.add(mineFragment)

        binding.bn.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.item_tab1 -> {
                    FragmentUtils.showAndHide(this, R.id.fl, homeFragment, fragmentList)
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab2 -> {
                    FragmentUtils.showAndHide(this, R.id.fl, gameFragment, fragmentList)
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab3 -> {
                    Log.e("3", "3")
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab4 -> {
                    FragmentUtils.showAndHide(this, R.id.fl, msgFragment, fragmentList)
                    return@OnNavigationItemSelectedListener true
                }
                R.id.item_tab5 -> {
                    FragmentUtils.showAndHide(this, R.id.fl, mineFragment, fragmentList)
                    return@OnNavigationItemSelectedListener true
                }

            }
            false
        })
    }

	/**
	* 状态栏设定,可忽略
	*/
    fun isTrans(isTrans: Boolean) {
        if (isTrans) {
            immersionBar {
                transparentStatusBar()
                navigationBarColor(R.color.gray)
                statusBarDarkFont(true)
            }
        } else {
            immersionBar {
                // fitsSystemWindows(true)
                statusBarColor(R.color.white)
                navigationBarColor(R.color.gray)
                autoDarkModeEnable(true)
            }
        }
    }

	/**
	* EventBus的一些操作,可忽略
	*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun changeStatus(switchFragmentEvent: SwitchFragmentEvent) {
        CoroutineScope(Dispatchers.IO).launch { DataStoreUtil.saveBooleanData("isChange", true) }
        isTrans(switchFragmentEvent.fragment is GameFragment)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        //关闭程序
        finishAffinity()
    }

FragmentUtils

2017

初级工具类,可以看后续的FragmentUtils(进行了二次封装)

package com.bengroup.uitls;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import com.bengroup.base.BaseFragment;


public class FragmentUtils {
	
	//继承BaseFragment
	public static void replaceFragment(FragmentActivity activity,int viewID,BaseFragment fragment){
		activity.getSupportFragmentManager().beginTransaction().replace(viewID, fragment).commit();
	}
	public static void show(FragmentActivity activity,Fragment fragment){
		activity.getSupportFragmentManager().beginTransaction().show(fragment).commit();
	}
	public static void hide(FragmentActivity activity,Fragment fragment){
		activity.getSupportFragmentManager().beginTransaction().hide(fragment).commit();
	}
	public static void remove(FragmentActivity activity){
		activity.getSupportFragmentManager().removeOnBackStackChangedListener(null);
	}
}
2022
package com.jsmedia.jsmanager.utils;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.jsmedia.jsmanager.event.SwitchFragmentEvent;
import com.tencent.qcloud.tuicore.component.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.List;


public class FragmentUtils {

    public static void replaceFragment(FragmentActivity activity, int viewID, BaseFragment fragment) {
        activity.getSupportFragmentManager().beginTransaction().replace(viewID, fragment).commit();
    }

    /**
     * fragmentLayout方式 - show 基础方法
     */
    public static void show(FragmentActivity activity, Fragment fragment) {
        activity.getSupportFragmentManager().beginTransaction().show(fragment).commit();
    }

    /**
     * fragmentLayout方式 - 显示指定fragment(hind、show)
     */
    public static void show(FragmentActivity activity, int fragmentId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(fragmentId, fragment).show(fragment);
        }
        //EventBus 可忽略,删除
        EventBus.getDefault().post(new SwitchFragmentEvent(fragment));
        fragmentTransaction.commit();
    }

    /**
     * fragmentLayout方式 : 显示指定的Fragment,同时隐藏其余Fragment(hind、show)
     */
    public static void showAndHide(FragmentActivity activity, int fragmentId, Fragment fragment, List<Fragment> fragmentList) {
        FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        if (fragmentList != null && fragmentList.size() > 0) {
            for (int i = 0; i < fragmentList.size(); i++) {
                fragmentTransaction.hide(fragmentList.get(i));
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(fragmentId, fragment).show(fragment);
        }
        //EventBus 可忽略,删除
        EventBus.getDefault().post(new SwitchFragmentEvent(fragment));
        fragmentTransaction.commit();
    }

    /**
     * fragmentLayout方式 - hide 基础方法
     */
    public static void hide(FragmentActivity activity, Fragment fragment) {
        activity.getSupportFragmentManager().beginTransaction().hide(fragment).commit();
    }

    /**
     * fragmentLayout方式 - 隐藏全部fragment
     */
    public static void hideAll(FragmentActivity activity, Fragment fragment, List<Fragment> fragmentList) {
        FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        if (fragmentList != null && fragmentList.size() > 0) {
            for (int i = 0; i < fragmentList.size(); i++) {
                fragmentTransaction.hide(fragmentList.get(i));
            }
        }
        fragmentTransaction.commit();
    }

    /**
     * fragmentLayout方式 - 可与showAndHide交替使用
     */
    public static void hideAndShow(FragmentActivity activity, Fragment fragment, List<Fragment> fragmentList) {
        FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        if (fragmentList != null && fragmentList.size() > 0) {
            for (int i = 0; i < fragmentList.size(); i++) {
                fragmentTransaction.hide(fragmentList.get(i));
            }
        }
        fragmentTransaction.show(fragment).commit();
    }

    public static void remove(FragmentActivity activity) {
        activity.getSupportFragmentManager().removeOnBackStackChangedListener(null);
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

远方那座山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值