【问题标题】:Replace fragment on nav host without destroying替换导航主机上的片段而不破坏
【发布时间】:2020-04-07 07:46:46
【问题描述】:

我正在使用 Android Jetpack Navigation 在我的应用程序中的片段之间导航,并使用单个 Main Activity。我在主要活动中有一个导航主机片段和一个底部导航,用于在片段之间导航。

navController = Navigation.findNavController(this,R.id.nav_host_fragment_container);
BottomNavigationView bottomNavigationView = findViewById(R.id.bot_nav_bar);
NavigationUI.setupWithNavController(bottomNavigationView,navController);

但是我有一个主要问题 - 每当我导航到另一个片段时,当前片段都会被销毁,当我返回时,它会与视图模型一起重新创建。然后视图模型再次从存储库中获取数据。

我该如何解决这个问题。我想在标签之间导航并加载其他片段而不破坏当前片段。

【问题讨论】:

  • 您的 ViewModel 不应在前进 -> 后退导航时被破坏。如果是,那么你没有正确初始化它......我想。虽然这是一个底部导航,但它可能。

标签: android android-fragments android-jetpack android-jetpack-navigation


【解决方案1】:

您必须创建您的自定义 NavHostFragment()。这里有一个简单的例子

https://medium.com/@programmerr47/navigate-back-with-navigation-component-6cec37ba6964

【讨论】:

    【解决方案2】:

    你可以的 1. 从片段 exp 创建对象:

    final Fragment frag1 = new Fragment1();
    final Fragment frag2 = new Fragment2();
    final Fragment frag3 = new Fragment3();
    

    在这之后你需要像这样从 FragmentManager 创建对象

    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = frag1;
    

    最后像这样将片段添加到 fm

    fm.beginTransaction().add(R.id.main_container, frag3, 
    "3").hide(frag3).commit();
    fm.beginTransaction().add(R.id.main_container, frag2, 
    "2").hide(frag2).commit();
    fm.beginTransaction().add(R.id.main_container,frag1, "1").commit();
    

    干得好,但不要忘记在 xml 文件中添加“main_container”

    main_container

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".view.activity.MainActivity"
    tools:showIn="@layout/activity_main"
    android:id="@+id/main_container">
    
    </FrameLayout>
    

    现在需要在YourActivity中添加

    <include
    layout="@layout/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
    

    现在在 actionListener 中

    fm.beginTransaction().hide(active).show(frag3).commit();
    active = frag3;
    

    【讨论】:

    • 在创建新实例之前,您应该始终尝试通过 findFragmentByTag 获取 Fragment 实例。
    猜你喜欢
    • 2018-03-24
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多