繁体   English   中英

导航拱形组件和碎片娱乐

[英]Navigation Arch Component and Fragments Recreation

我用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>

而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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM