android - 导航拱形组件和 fragment 娱乐

标签 android android-architecture-components android-architecture-navigation

我将BottomNavigationViewNavHostFragment一起使用,目前只有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>




而BottomNavigation菜单是:

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




问题是,每次我在选项卡之间切换时,它都会创建一个我单击的选项卡片段的新实例,是否有一种方法可以管理这种情况,以防止在内存中已经存在新项目的情况下进行创建?

最佳答案

我的回答仅限于Java。但是你会明白的:

在BottomNavigationView上单击,尝试按id查找片段,如果它存在于内存中,则无需创建一个片段,

ListingFragment listingFragment
if (findViewById(R.id.fragment1) != null) {
 listingFragment  = findViewById(R.id.fragment1);
}
// if the listing fragment is null then create new one
else{
  listingFragment = new ListingFragment();
}
 getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();


或者您可以根据需要将其添加到堆栈中。

关于android - 导航拱形组件和 fragment 娱乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947341/

相关文章:

android - 访问共享首选项存储库中的 appcontext(架构)

安卓读取cookies

android - 将 LinearLayout 放置在工具栏下方

Android:在 ViewModel 中获取 DAO

android - 如何清除/删除页面列表适配器中的所有项目

android - 导航架构组件 - 带有登录屏幕的 BottomNavigationView

Android jetpack 导航组件来自对话框

Webview 中的 Android 自定义键盘跳帧

android - 如果状态由我的类组成,如何在 Android 中的方向更改期间保存状态?

android - Jetpack 导航组件上具有不同行为的后退和向上按钮