簡體   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