首页 > 解决方案 > 导航拱组件和碎片娱乐

问题描述

BottomNavigationView一起使用NavHostFragment,目前只有 2 个选项卡,位于我使用的导航图下方

<?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/main_navigation"
  app:startDestination="@id/fragment1">

  <fragment
    android:id="@+id/fragment1"
    android:name="something.ListingFragment"
    android:label="@string/hello" />

  <fragment
    android:id="@+id/fragment2"
    android:name="something.ListingFragment2"
    android:label="@string/Hi" />

</navigation>

而底部导航菜单是:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools">
  <item
    android:id="@id/fragment1"
    android:icon="@drawable/ic1"
    android:title="@string/hello"
    tools:showAsAction="ifRoom" />
  <item
    android:id="@id/fragment2"
    android:icon="@drawable/ic2"
    android:title="@string/hi"
    tools:showAsAction="ifRoom" />

所有设置一起使用:

val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
    val navHostFragment = supportFragmentManager.findFragmentById(R.id.navigation_host_fragment) as NavHostFragment
    NavigationUI.setupWithNavController(bottomNavigationView, navHostFragment.navController)

问题是,每次我在选项卡之间切换时,它都会创建一个我单击的选项卡片段的新实例,如果内存中已经存在新项目,是否有办法管理它以防止创建新项目?

标签: androidandroid-architecture-componentsandroid-architecture-navigation

解决方案


推荐阅读