【问题标题】:How do one set an ID for a fragment displayed by a NavController and creating a Fragment object?如何为 NavController 显示的片段设置 ID 并创建片段对象?
【发布时间】:2022-11-15 12:00:14
【问题描述】:

我创建了一个导航栏,但我不明白如何为 grph 中的每个片段创建一个 ID。

导航图:

<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/nav_graph"
    app:startDestination="@id/nav_home">
    <fragment
        android:id="@+id/nav_home"
        android:name="com.mordechay.yemotapp.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >
    </fragment>
    <fragment
        android:id="@id/nav_explorer"
        android:name="com.mordechay.yemotapp.filseExplorerFragment"
        android:label="fragment_filse_explorer"
        tools:layout="@layout/fragment_filse_explorer" />
</navigation>

在活动中:

<fragment
    android:id="@+id/nvgv_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintTop_toBottomOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/nav_graph"
    />

我在活动中写道:

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_explorer);

结果是空的,我需要写什么来获取片段?

我试图通过写入在导航图中找到的片段的 ID 来获取片段。 但我得到空。

【问题讨论】:

    标签: java android android-fragments android-navigation-graph


    【解决方案1】:

    你已经设置了你的 id => android:id="@+id/nav_home" 和 android:id="@+id/nav_explorer"。

    首先,您需要声明您的导航控制器。

    val navigationController = findNavController(R.id.nvgv_fragment)
    

    然后你可以用监听器检查目标片段

    navigationController.addOnDestinationChangedListener { _, destination, _ ->
        if (destination.id == R.id.nav_explorer) {
            // whatever you want to do
        }
    }
    

    但是,如果您只需要一个显示片段的实例,您可以在这里找到答案: Current fragment instance

    【讨论】:

    • 它确实起作用了。但是还是获取不到fragment对象,你是怎么获取到feagment对象的?我写了它,但片段仍然是空的。如果 (navDestination.getId() == R.id.nav_explorer) { fragment = getSupportFragmentManager().findFragmentById(R.id.nav_explorer); }
    • 我需要这个来实现这个:stackoverflow.com/a/46425415/19169874
    • 好的。你可以找到类似这样的片段实例: // 用片段做任何你想做的事 } }
    • 在 Java 中如何?
    • void findFragmentInstance() { Fragment fragmentHost = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); List<Fragment> fragmentList = fragmentHost.getChildFragmentManager().getFragments();片段 fr = fragmentList.get(fragmentList.size() - 1); if (fr instanceof YourFragment) { // 对片段做任何你想做的事 } } // 注意,fragmentHost、childFragmentManager 和 fragmentsList 可能为空。您需要检查它以避免 NullPointerException。希望这可以帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多