Android Jetpack 导航,使用 Youtube 或 Instagram 的 BottomNavigationView,像正确的后向导航(片段后向堆栈) ?

安卓喷气背包导航,底部导航视图与自动片段堆栈后退按钮点击?

我想要的是,在用户选择多个标签后,用户点击后退按钮应用程序必须重定向到他/她打开的最后一个页面。

我使用 Android ViewPager 实现了同样的目标,将当前选定的项保存在 ArrayList 中。安卓喷气背包导航发布后有没有自动回栈?我想实现它使用导航图

Activity _ main. xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.MainActivity">


<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_graph" />


<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation" />


</android.support.constraint.ConstraintLayout>

Xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">


<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home"
android:title="@string/title_home" />


<item
android:id="@+id/navigation_people"
android:icon="@drawable/ic_group"
android:title="@string/title_people" />


<item
android:id="@+id/navigation_organization"
android:icon="@drawable/ic_organization"
android:title="@string/title_organization" />


<item
android:id="@+id/navigation_business"
android:icon="@drawable/ic_business"
android:title="@string/title_business" />


<item
android:id="@+id/navigation_tasks"
android:icon="@drawable/ic_dashboard"
android:title="@string/title_tasks" />


</menu>

还增加了

bottomNavigation.setupWithNavController(Navigation.findNavController(this, R.id.my_nav_host_fragment))

我从 Levi Moreira得到一个答案,如下

navigation.setOnNavigationItemSelectedListener {item ->


onNavDestinationSelected(item, Navigation.findNavController(this, R.id.my_nav_host_fragment))


}

但是这样做的唯一结果是上次打开的片段的实例再次创建。

为 BottomNavigationView 提供正确的反向导航

65358 次浏览

您可以设置带有底部导航视图的视图页导航器。视图页面中的每个片段都将是一个容器片段,它将拥有带有自己的回栈的子片段。您可以通过这种方式为视图页面中的每个选项卡维护回栈

您实际上并不需要 ViewPager来处理 BottomNavigation和新的导航体系结构组件。我一直在一个示例应用程序,使用正好两个,见 给你

基本的概念是这样的,你有主要的活动,将主机的 BottomNavigationView和导航主机为您的导航图,这是它的 xml 看起来像:

Activity _ main. xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.MainActivity">


<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_graph" />


<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation" />


</android.support.constraint.ConstraintLayout>

BottomNavigationView的导航菜单(选项卡菜单)如下:

Xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">


<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home"
android:title="@string/title_home" />


<item
android:id="@+id/navigation_people"
android:icon="@drawable/ic_group"
android:title="@string/title_people" />


<item
android:id="@+id/navigation_organization"
android:icon="@drawable/ic_organization"
android:title="@string/title_organization" />


<item
android:id="@+id/navigation_business"
android:icon="@drawable/ic_business"
android:title="@string/title_business" />


<item
android:id="@+id/navigation_tasks"
android:icon="@drawable/ic_dashboard"
android:title="@string/title_tasks" />


</menu>

所有这些都只是 BottomNavigationView设置。现在,为了让它与导航拱组件一起工作,你需要进入导航图编辑器,添加所有的片段目的地(在我的例子中,我有5个片段目的地,每个标签一个) ,并设置目的地的 id 与 navigation.xml文件中的名称相同:

enter image description here

这将告诉 android 在选项卡和片段之间建立一个链接,现在每当用户点击“ Home”选项卡时,android 将负责加载正确的片段。 还有一段 kotlin 代码需要添加到您的 NavHost (主要活动)中,以便将事情与 BottomNavigationView连接起来:

您需要添加 onCreate:

bottomNavigation.setupWithNavController(Navigation.findNavController(this, R.id.my_nav_host_fragment))

这告诉 android 在导航体系结构组件和 BottomNavigationView 之间进行连接。

如果你想像使用 youtube 一样,只需要添加以下内容:

navigation.setOnNavigationItemSelectedListener {item ->


onNavDestinationSelected(item, Navigation.findNavController(this, R.id.my_nav_host_fragment))


}

这将使目的地进入回栈,所以当您按下后退按钮,最后访问的目的地将弹出。

我做了一个像这样的应用程序(仍然没有在 PlayStore 上发布) ,有相同的导航,也许它的实现不同于谷歌在他们的应用程序,但功能是相同的。

结构涉及到我有主活动,我切换它的内容,通过显示/隐藏片段使用:

public void switchTo(final Fragment fragment, final String tag /*Each fragment should have a different Tag*/) {


// We compare if the current stack is the current fragment we try to show
if (fragment == getSupportFragmentManager().getPrimaryNavigationFragment()) {
return;
}


// We need to hide the current showing fragment (primary fragment)
final Fragment currentShowingFragment = getSupportFragmentManager().getPrimaryNavigationFragment();


final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (currentShowingFragment != null) {
fragmentTransaction.hide(currentShowingFragment);
}


// We try to find that fragment if it was already added before
final Fragment alreadyAddedFragment = getSupportFragmentManager().findFragmentByTag(tag);
if (alreadyAddedFragment != null) {
// Since its already added before we just set it as primary navigation and show it again
fragmentTransaction.setPrimaryNavigationFragment(alreadyAddedFragment);
fragmentTransaction.show(alreadyAddedFragment);
} else {
// We add the new fragment and then show it
fragmentTransaction.add(containerId, fragment, tag);
fragmentTransaction.show(fragment);
// We set it as the primary navigation to support back stack and back navigation
fragmentTransaction.setPrimaryNavigationFragment(fragment);
}


fragmentTransaction.commit();
}

您必须像下面的 xml 那样设置主机导航:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">


<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary" />


<fragment
android:id="@+id/navigation_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />


<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemIconTint="@drawable/color_state_list"
app:itemTextColor="@drawable/color_state_list"
app:menu="@menu/menu_bottom_navigation" />
</LinearLayout>

安装导航控制器:

NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_host_fragment);
NavigationUI.setupWithNavController(bottomNavigationView, navHostFragment.getNavController());

Menu _ bottom _ Navigation.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@id/tab1"  // Id of navigation graph
android:icon="@mipmap/ic_launcher"
android:title="@string/tab1" />
<item
android:id="@id/tab2" // Id of navigation graph
android:icon="@mipmap/ic_launcher"
android:title="@string/tab2" />


<item
android:id="@id/tab3" // Id of navigation graph
android:icon="@mipmap/ic_launcher"
android:title="@string/tab3" />
</menu>

Nav _ graph.xml:

<navigation 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:id="@+id/nav_graph"
app:startDestination="@id/tab1">
<fragment
android:id="@+id/tab1"
android:name="com.navigationsample.Tab1Fragment"
android:label="@string/tab1"
tools:layout="@layout/fragment_tab_1" />


<fragment
android:id="@+id/tab2"
android:name="com.navigationsample.Tab2Fragment"
android:label="@string/tab2"
tools:layout="@layout/fragment_tab_2"/>


<fragment
android:id="@+id/tab3"
android:name="com.simform.navigationsample.Tab3Fragment"
android:label="@string/tab3"
tools:layout="@layout/fragment_tab_3"/>
</navigation>

通过将“ nav _ graph”的 id 设置为“ menu _ bottom _ ”,就可以處理按下下方导航键。

可以使用 action标记中的 popUpTo属性处理反向操作。 enter image description here

如果你有一个 bottomNavigationView,其中有3个项目对应于3个 Fragment: FragmentAFragmentBFragmentC,其中 FragmentA是导航图中的 startDestination,那么当你在 FragmentBFragmentC上点击返回时,你将被重定向到 FragmentA,这是谷歌推荐的行为,默认实现。

无论如何,如果你想改变这种行为,你需要使用 ViewPager作为建议的其他一些答案,或手动处理片段回栈和回事务自己-这在某种程度上会削弱导航组件的使用-。

首先,让我解释一下 Youtube 和 Instagram 是如何处理片段导航的。

  • 当用户处于一个细节片段上时,返回或向上弹出堆栈一次,使状态得到适当的恢复。第二次单击已经选择的底部条目,将所有堆栈弹出到根目录,刷新它
  • 当用户处于根片段时,返回到底部栏上选择的最后一个菜单,显示最后一个细节片段,状态恢复正常(JetPack 没有恢复)
  • 当用户处于开始目标片段时,back 完成活动

上面的其他答案都没有用 Jetpack 导航解决所有这些问题。

JetPack 导航没有标准的方法来做到这一点,我发现更简单的方法是将导航 xml 图划分为每个底部导航条目的一个,使用活动 FragmentManager 处理导航条目之间的回栈,并使用 JetPack NavController 处理根片段和细节片段之间的内部导航(它的实现使用 child FragmentManager 栈)。

假设在 navigation文件夹中有3个 xml:

res/navigation/
navigation_feed.xml
navigation_explore.xml
navigation_profile.xml

在导航 xmls 中设置与下面的 NavigationBar 菜单 id 相同的 DestinationID。另外,对于每个 xml,将 app:startDestination设置为您希望作为导航项的根的片段。

创建一个类 BottomNavController.kt:

class BottomNavController(
val context: Context,
@IdRes val containerId: Int,
@IdRes val appStartDestinationId: Int
) {
private val navigationBackStack = BackStack.of(appStartDestinationId)
lateinit var activity: Activity
lateinit var fragmentManager: FragmentManager
private var listener: OnNavigationItemChanged? = null
private var navGraphProvider: NavGraphProvider? = null


interface OnNavigationItemChanged {
fun onItemChanged(itemId: Int)
}


interface NavGraphProvider {
@NavigationRes
fun getNavGraphId(itemId: Int): Int
}


init {
var ctx = context
while (ctx is ContextWrapper) {
if (ctx is Activity) {
activity = ctx
fragmentManager = (activity as FragmentActivity).supportFragmentManager
break
}
ctx = ctx.baseContext
}
}


fun setOnItemNavigationChanged(listener: (itemId: Int) -> Unit) {
this.listener = object : OnNavigationItemChanged {
override fun onItemChanged(itemId: Int) {
listener.invoke(itemId)
}
}
}


fun setNavGraphProvider(provider: NavGraphProvider) {
navGraphProvider = provider
}


fun onNavigationItemReselected(item: MenuItem) {
// If the user press a second time the navigation button, we pop the back stack to the root
activity.findNavController(containerId).popBackStack(item.itemId, false)
}


fun onNavigationItemSelected(itemId: Int = navigationBackStack.last()): Boolean {


// Replace fragment representing a navigation item
val fragment = fragmentManager.findFragmentByTag(itemId.toString())
?: NavHostFragment.create(navGraphProvider?.getNavGraphId(itemId)
?: throw RuntimeException("You need to set up a NavGraphProvider with " +
"BottomNavController#setNavGraphProvider")
)
fragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.nav_default_enter_anim,
R.anim.nav_default_exit_anim,
R.anim.nav_default_pop_enter_anim,
R.anim.nav_default_pop_exit_anim
)
.replace(containerId, fragment, itemId.toString())
.addToBackStack(null)
.commit()


// Add to back stack
navigationBackStack.moveLast(itemId)


listener?.onItemChanged(itemId)


return true
}


fun onBackPressed() {
val childFragmentManager = fragmentManager.findFragmentById(containerId)!!
.childFragmentManager
when {
// We should always try to go back on the child fragment manager stack before going to
// the navigation stack. It's important to use the child fragment manager instead of the
// NavController because if the user change tabs super fast commit of the
// supportFragmentManager may mess up with the NavController child fragment manager back
// stack
childFragmentManager.popBackStackImmediate() -> {
}
// Fragment back stack is empty so try to go back on the navigation stack
navigationBackStack.size > 1 -> {
// Remove last item from back stack
navigationBackStack.removeLast()


// Update the container with new fragment
onNavigationItemSelected()
}
// If the stack has only one and it's not the navigation home we should
// ensure that the application always leave from startDestination
navigationBackStack.last() != appStartDestinationId -> {
navigationBackStack.removeLast()
navigationBackStack.add(0, appStartDestinationId)
onNavigationItemSelected()
}
// Navigation stack is empty, so finish the activity
else -> activity.finish()
}
}


private class BackStack : ArrayList<Int>() {
companion object {
fun of(vararg elements: Int): BackStack {
val b = BackStack()
b.addAll(elements.toTypedArray())
return b
}
}


fun removeLast() = removeAt(size - 1)
fun moveLast(item: Int) {
remove(item)
add(item)
}
}
}


// Convenience extension to set up the navigation
fun BottomNavigationView.setUpNavigation(bottomNavController: BottomNavController, onReselect: ((menuItem: MenuItem) -> Unit)? = null) {
setOnNavigationItemSelectedListener {
bottomNavController.onNavigationItemSelected(it.itemId)
}
setOnNavigationItemReselectedListener {
bottomNavController.onNavigationItemReselected(it)
onReselect?.invoke(it)
}
bottomNavController.setOnItemNavigationChanged { itemId ->
menu.findItem(itemId).isChecked = true
}
}

你的布局如下:

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


<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/bottomNavigationView"
app:layout_constraintTop_toTopOf="parent" />


<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/navigation" />


</androidx.constraintlayout.widget.ConstraintLayout>

在你的活动中使用如下:

class MainActivity : AppCompatActivity(),
BottomNavController.NavGraphProvider  {


private val navController by lazy(LazyThreadSafetyMode.NONE) {
Navigation.findNavController(this, R.id.container)
}


private val bottomNavController by lazy(LazyThreadSafetyMode.NONE) {
BottomNavController(this, R.id.container, R.id.navigation_feed)
}


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)


bottomNavController.setNavGraphProvider(this)
bottomNavigationView.setUpNavigation(bottomNavController)
if (savedInstanceState == null) bottomNavController
.onNavigationItemSelected()


// do your things...
}


override fun getNavGraphId(itemId: Int) = when (itemId) {
R.id.navigation_feed -> R.navigation.navigation_feed
R.id.navigation_explore -> R.navigation.navigation_explore
R.id.navigation_profile -> R.navigation.navigation_profile
else -> R.navigation.navigation_feed
}


override fun onSupportNavigateUp(): Boolean = navController
.navigateUp()


override fun onBackPressed() = bottomNavController.onBackPressed()
}

Kotlin 用于连接底部导航项和导航内部片段的简短而优秀的代码图片来源:

    val navControl = findNavController( R.id.nav_host_frag_main)
bottomNavigationView?.setupWithNavController(navControl)

考虑一下: 导航图中底部的导航 id 和片段必须具有相同的 id。 还要感谢@sanat 的解释

最好的解决方案是由谷歌团队提供的解决方案,他的回购,返回按钮仍然发送你回到第一个按钮,但其余的行为是“正常的”... 这看起来很奇怪,谷歌仍然没有提供一个好的解决方案,即使当他们正在使用它在(youtube,谷歌照片等) ,他们说 androidx 是有帮助的,但看起来只是我们四处走走,找到一个解决方案的正常的东西。

这里是谷歌回购的链接,他们正在使用导航。底部与导航图每个按钮。 Https://github.com/android/architecture-components-samples/blob/master/navigationadvancedsample/app/src/main/java/com/example/android/navigationadvancedsample/navigationextensions.kt 将这个文件复制到你的项目中,看看它是如何在他们的项目中实现的。对于后退按钮的行为,您可以创建一个自己的堆栈和 onBackpress 只是在该堆栈上导航。

我没有找到任何正式的解决方案,但我用我自己的方式

首先,我为句柄片段创建 Stack

    needToAddToBackStack : Boolen = true




private lateinit var fragmentBackStack: Stack<Int>
fragmentBackStack = Stack()

进去

navController.addOnDestinationChangedListener { _, destination, _ ->
if (needToAddToBackStack) {
fragmentBackStack.add(destination.id)
}




needToAddToBackStack = true


}

按下后面的按钮

override fun onBackPressed() {
if (::fragmentBackStack.isInitialized && fragmentBackStack.size > 1) {
fragmentBackStack.pop()
val fragmentId = fragmentBackStack.lastElement()
needToAddToBackStack = false
navController.navigate(fragmentId)


} else {
if (::fragmentBackStack.isInitialized && fragmentBackStack.size == 1) {
finish()
} else {
super.onBackPressed()
}
}

看完你的问题后,我又查看了谷歌文档。我看到他们已经提供了一个解决方案,使导航用户界面与 BottomNavigationView 工作得很好。所以,我为所有像我一样需要它的人创建了一个教程。 文字版本: https://nhatvm.com/how-to-use-navigationui-with-bottomnavigation-in-android/ 对于 youtube 版本,请点击: http://youtu.be/2uxILvBbkyY rel = “ nofollow norefrer”> https://youtu.be/2uxilvbbkyy

保持状态的适当回栈的关键点是拥有 NavHostFragmentNavHostFragment具有 child FragmentManager 和它们自己的回栈。导航组件的高级示例的扩展文件实际上是这样做的。

/**
* Manages the various graphs needed for a [BottomNavigationView].
*
* This sample is a workaround until the Navigation Component supports multiple back stacks.
*/
fun BottomNavigationView.setupWithNavController(
navGraphIds: List<Int>,
fragmentManager: FragmentManager,
containerId: Int,
intent: Intent
): LiveData<NavController> {


// Map of tags
val graphIdToTagMap = SparseArray<String>()
// Result. Mutable live data with the selected controlled
val selectedNavController = MutableLiveData<NavController>()


var firstFragmentGraphId = 0


// First create a NavHostFragment for each NavGraph ID
navGraphIds.forEachIndexed { index, navGraphId ->
val fragmentTag = getFragmentTag(index)


// Find or create the Navigation host fragment
val navHostFragment = obtainNavHostFragment(
fragmentManager,
fragmentTag,
navGraphId,
containerId
)


// Obtain its id
val graphId = navHostFragment.navController.graph.id


if (index == 0) {
firstFragmentGraphId = graphId
}


// Save to the map
graphIdToTagMap[graphId] = fragmentTag


// Attach or detach nav host fragment depending on whether it's the selected item.
if (this.selectedItemId == graphId) {
// Update livedata with the selected graph
selectedNavController.value = navHostFragment.navController
attachNavHostFragment(fragmentManager, navHostFragment, index == 0)
} else {
detachNavHostFragment(fragmentManager, navHostFragment)
}
}


// Now connect selecting an item with swapping Fragments
var selectedItemTag = graphIdToTagMap[this.selectedItemId]
val firstFragmentTag = graphIdToTagMap[firstFragmentGraphId]
var isOnFirstFragment = selectedItemTag == firstFragmentTag


// When a navigation item is selected
setOnNavigationItemSelectedListener { item ->
// Don't do anything if the state is state has already been saved.
if (fragmentManager.isStateSaved) {
false
} else {
val newlySelectedItemTag = graphIdToTagMap[item.itemId]
if (selectedItemTag != newlySelectedItemTag) {
// Pop everything above the first fragment (the "fixed start destination")
fragmentManager.popBackStack(
firstFragmentTag,
FragmentManager.POP_BACK_STACK_INCLUSIVE
)
val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag)
as NavHostFragment


// Exclude the first fragment tag because it's always in the back stack.
if (firstFragmentTag != newlySelectedItemTag) {
// Commit a transaction that cleans the back stack and adds the first fragment
// to it, creating the fixed started destination.
fragmentManager.beginTransaction()
.attach(selectedFragment)
.setPrimaryNavigationFragment(selectedFragment)
.apply {
// Detach all other Fragments
graphIdToTagMap.forEach { _, fragmentTagIter ->
if (fragmentTagIter != newlySelectedItemTag) {
detach(fragmentManager.findFragmentByTag(firstFragmentTag)!!)
}
}
}
.addToBackStack(firstFragmentTag)
.setCustomAnimations(
R.anim.nav_default_enter_anim,
R.anim.nav_default_exit_anim,
R.anim.nav_default_pop_enter_anim,
R.anim.nav_default_pop_exit_anim
)
.setReorderingAllowed(true)
.commit()
}
selectedItemTag = newlySelectedItemTag
isOnFirstFragment = selectedItemTag == firstFragmentTag
selectedNavController.value = selectedFragment.navController
true
} else {
false
}
}
}


// Optional: on item reselected, pop back stack to the destination of the graph
setupItemReselected(graphIdToTagMap, fragmentManager)


// Handle deep link
setupDeepLinks(navGraphIds, fragmentManager, containerId, intent)


// Finally, ensure that we update our BottomNavigationView when the back stack changes
fragmentManager.addOnBackStackChangedListener {
if (!isOnFirstFragment && !fragmentManager.isOnBackStack(firstFragmentTag)) {
this.selectedItemId = firstFragmentGraphId
}


// Reset the graph if the currentDestination is not valid (happens when the back
// stack is popped after using the back button).
selectedNavController.value?.let { controller ->
if (controller.currentDestination == null) {
controller.navigate(controller.graph.id)
}
}
}
return selectedNavController
}


private fun BottomNavigationView.setupDeepLinks(
navGraphIds: List<Int>,
fragmentManager: FragmentManager,
containerId: Int,
intent: Intent
) {
navGraphIds.forEachIndexed { index, navGraphId ->
val fragmentTag = getFragmentTag(index)


// Find or create the Navigation host fragment
val navHostFragment = obtainNavHostFragment(
fragmentManager,
fragmentTag,
navGraphId,
containerId
)
// Handle Intent
if (navHostFragment.navController.handleDeepLink(intent)
&& selectedItemId != navHostFragment.navController.graph.id
) {
this.selectedItemId = navHostFragment.navController.graph.id
}
}
}


private fun BottomNavigationView.setupItemReselected(
graphIdToTagMap: SparseArray<String>,
fragmentManager: FragmentManager
) {
setOnNavigationItemReselectedListener { item ->
val newlySelectedItemTag = graphIdToTagMap[item.itemId]
val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag)
as NavHostFragment
val navController = selectedFragment.navController
// Pop the back stack to the start destination of the current navController graph
navController.popBackStack(
navController.graph.startDestination, false
)
}
}


private fun detachNavHostFragment(
fragmentManager: FragmentManager,
navHostFragment: NavHostFragment
) {
fragmentManager.beginTransaction()
.detach(navHostFragment)
.commitNow()
}


private fun attachNavHostFragment(
fragmentManager: FragmentManager,
navHostFragment: NavHostFragment,
isPrimaryNavFragment: Boolean
) {
fragmentManager.beginTransaction()
.attach(navHostFragment)
.apply {
if (isPrimaryNavFragment) {
setPrimaryNavigationFragment(navHostFragment)
}
}
.commitNow()


}


private fun obtainNavHostFragment(
fragmentManager: FragmentManager,
fragmentTag: String,
navGraphId: Int,
containerId: Int
): NavHostFragment {
// If the Nav Host fragment exists, return it
val existingFragment = fragmentManager.findFragmentByTag(fragmentTag) as NavHostFragment?
existingFragment?.let { return it }


// Otherwise, create it and return it.
val navHostFragment = NavHostFragment.create(navGraphId)
fragmentManager.beginTransaction()
.add(containerId, navHostFragment, fragmentTag)
.commitNow()
return navHostFragment
}


private fun FragmentManager.isOnBackStack(backStackName: String): Boolean {
val backStackCount = backStackEntryCount
for (index in 0 until backStackCount) {
if (getBackStackEntryAt(index).name == backStackName) {
return true
}
}
return false
}


private fun getFragmentTag(index: Int) = "bottomNavigation#$index"

这里的重要部分是获取 NavHostFragment,如果它与上面的函数不存在于回堆栈中,并将其添加到回堆栈中。与 commit不同,commitNow是同步的

私人乐趣获取 NavHostFragment ( 片段管理器: 字符串, NavGraphId: Int, Container erId: Int ) : NavHostFragment { //如果存在导航主机片段,则返回它 作为 NavHostFragment? 是否存在碎片? 让{返回它}

// Otherwise, create it and return it.
val navHostFragment = NavHostFragment.create(navGraphId)
fragmentManager.beginTransaction()
.add(containerId, navHostFragment, fragmentTag)
.commitNow()
return navHostFragment

}

我使用上面的导航扩展构建了一个类似于这样的扩展

BottomNavigationView with Navigation Component

嵌套导航。

导航图是相似的,所以我只添加一个

Nav _ graph _ home. xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph_home"
app:startDestination="@id/homeFragment1">




<fragment
android:id="@+id/homeFragment1"
android:name="com.smarttoolfactory.tutorial5_3navigationui_bottomnavigation_nestednavigation.blankfragment.HomeFragment1"
android:label="HomeFragment1"
tools:layout="@layout/fragment_home1">
<action
android:id="@+id/action_homeFragment1_to_homeFragment2"
app:destination="@id/homeFragment2" />
</fragment>


<fragment
android:id="@+id/homeFragment2"
android:name="com.smarttoolfactory.tutorial5_3navigationui_bottomnavigation_nestednavigation.blankfragment.HomeFragment2"
android:label="HomeFragment2"
tools:layout="@layout/fragment_home2">
<action
android:id="@+id/action_homeFragment2_to_homeFragment3"
app:destination="@id/homeFragment3" />
</fragment>


<fragment
android:id="@+id/homeFragment3"
android:name="com.smarttoolfactory.tutorial5_3navigationui_bottomnavigation_nestednavigation.blankfragment.HomeFragment3"
android:label="HomeFragment3"
tools:layout="@layout/fragment_home3" >
<action
android:id="@+id/action_homeFragment3_to_homeFragment1"
app:destination="@id/homeFragment1"
app:popUpTo="@id/homeFragment1"
app:popUpToInclusive="true" />
</fragment>


</navigation>

底部导航菜单

Menu _ bottom _ nav. xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">


<item
android:id="@+id/nav_graph_home"
android:icon="@drawable/ic_baseline_home_24"
android:title="Home"/>


<item
android:id="@+id/nav_graph_dashboard"
android:icon="@drawable/ic_baseline_dashboard_24"
android:title="Dashboard"/>


<item
android:id="@+id/nav_graph_notification"
android:icon="@drawable/ic_baseline_notifications_24"
android:title="Notification"/>
    

</menu>

包含 FragmentContainerViewBottomNavigationView的 MainActivity 的布局

Activy _ main. xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">


<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottom_nav"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />


<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/menu_bottom_nav" />


</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {


private var currentNavController: LiveData<NavController>? = null


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)


supportFragmentManager.addOnBackStackChangedListener {
val backStackEntryCount = supportFragmentManager.backStackEntryCount
val fragments = supportFragmentManager.fragments
val fragmentCount = fragments.size




Toast.makeText(
this,
"MainActivity backStackEntryCount: $backStackEntryCount, fragmentCount: $fragmentCount, fragments: $fragments",
Toast.LENGTH_SHORT
).show()
}




if (savedInstanceState == null) {
setupBottomNavigationBar()
} // Else, need to wait for onRestoreInstanceState
}


override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
// Now that BottomNavigationBar has restored its instance state
// and its selectedItemId, we can proceed with setting up the
// BottomNavigationBar with Navigation
setupBottomNavigationBar()
}


/**
* Called on first creation and when restoring state.
*/
private fun setupBottomNavigationBar() {
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)


val navGraphIds = listOf(
R.navigation.nav_graph_home,
R.navigation.nav_graph_dashboard,
R.navigation.nav_graph_notification
)


// Setup the bottom navigation view with a list of navigation graphs
val controller = bottomNavigationView.setupWithNavController(
navGraphIds = navGraphIds,
fragmentManager = supportFragmentManager,
containerId = R.id.nav_host_container,
intent = intent
)
// Whenever the selected controller changes, setup the action bar.
controller.observe(this, Observer { navController ->
setupActionBarWithNavController(navController)
})
currentNavController = controller
}


override fun onSupportNavigateUp(): Boolean {
return currentNavController?.value?.navigateUp() ?: false
}
}

片段布局和类是简单的类,所以我跳过了它们。您可以查看构建的 完整样本i 或 谷歌的资源库来检查高级导航或其他示例的扩展。

原答案在这里: https://stackoverflow.com/a/63645978/8956093

在 Jetpack 导航组件中,如果希望在弹出片段时执行某些操作,则需要重写以下函数。

  1. 在片段中添加 OnBackPresdedCallback,以便在系统导航栏底部按下 back 时运行特殊操作。

     override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    
    onBackPressedCallback = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
    //perform your operation and call navigateUp
    findNavController().navigateUp()
    }
    }
    requireActivity().onBackPressedDispatcher.addCallback(onBackPressedCallback)
    }
    
  2. 在片段中添加 onOptionsItemMenu 来处理应用程序中左上角出现的向后箭头按钮。

     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    
    setHasOptionsMenu(true)
    }
    
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) {
    //perform your operation and call navigateUp
    findNavController().navigateUp()
    return true
    }
    return super.onOptionsItemSelected(item)
    }
    
  3. 如果在主机片段上按回车键时没有要运行的特殊代码,那么在 Activity 中使用 onSupportNavigateUp。

     override fun onSupportNavigateUp(): Boolean {
    if (navController.navigateUp() == false){
    //navigateUp() returns false if there are no more fragments to pop
    onBackPressed()
    }
    return navController.navigateUp()
    }
    

注意,如果片段包含 onOptionsItemSelected () ,则不调用 onSupportNavigateUp ()

在导航包的2.4.0版本中,它终于得到了官方的支持!

Https://developer.android.com/jetpack/androidx/releases/navigation#version_240_2

不仅如此: 在将导航库上传到这个版本之后,这个特性就是 违约行为。顺便说一句,现在这个默认行为包括片段在它们之间导航时不会重新创建,即 似乎有些事情我们很需要