导航到目的地时仅创建一个片段实例(android)

Ale*_*ili 10 navigation android navigationcontroller android-fragments android-studio

我正在使用导航组件。导航时我不想创建新的片段实例,如果它已经存在于 backstack 中并弹出前面已经存在的片段。

    findNavController().navigate(RequestTransferFragmentDirections.actionRequestTransferFragmentToBlankFragment())
Run Code Online (Sandbox Code Playgroud)

寻找解决方案。

谢谢。

Nen*_*idt 6

我在这种模式下只实现了一个fragment类型实例的请求:

在 navigation_graph.xml 中,我声明了一个到fragment-destination的popUp-action

<action
    android:id="@+id/home_action"
    app:destination="@id/my_dest"
    app:popUpTo="@id/my_dest"
    app:popUpToInclusive="true" />

<fragment
    android:id="@+id/my_dest"
    android:name="com.project.android.fragments.MyFragment"
    android:label=""
    tools:layout="@layout/my_fragment_layout" />
Run Code Online (Sandbox Code Playgroud)

在代码中我调用该操作

navController.navigate(R.id.home_action)
Run Code Online (Sandbox Code Playgroud)


Joh*_*mez 5

因为我也有同样的问题所以在这里回答。以下是对我有用的解决方案。我最终使用了导航控制器并弹出到后退堆栈目的地(如果存在),如果不存在,则我正常导航到它。

这看起来像这样:

if ( ! nav.popBackStack(R.id.action_profile, false)) {
    nav.navigate(R.id.action_profile)
}
Run Code Online (Sandbox Code Playgroud)

nav.popBackStack(R.id.action_profile, false)如果传入的目的地不在后台堆栈中,则返回 false,否则将弹出到后台堆栈,如果在,则返回 true。该布尔值也用于弹出目标片段。

来自文档:

/**
     * Attempts to pop the controller's back stack back to a specific destination.
     *
     * @param destinationId The topmost destination to retain
     * @param inclusive Whether the given destination should also be popped.
     *
     * @return true if the stack was popped at least once and the user has been navigated to
     * another destination, false otherwise
     */
    public boolean popBackStack(@IdRes int destinationId, boolean inclusive) {
        boolean popped = popBackStackInternal(destinationId, inclusive);
        // Only return true if the pop succeeded and we've dispatched
        // the change to a new destination
        return popped && dispatchOnDestinationChanged();
    }

Run Code Online (Sandbox Code Playgroud)


Mig*_*cia 5

我遇到了同样的问题,但不幸的是,以前的解决方案对我不起作用,尽管他们应该解决这个问题。谢谢顺便说一句!:)

这对我有用,适合您的代码是:

findNavController().navigate(
    RequestTransferFragmentDirections.actionRequestTransferFragmentToBlankFragment()),
    NavOptions.Builder().setLaunchSingleTop(true).build()
)
Run Code Online (Sandbox Code Playgroud)

我在navigate()文档中看到我们可以传递options,因此通过传递NavOptions.Builder().setLaunchSingleTop(true).build()将创建此类片段的单个实例。