在导航控制器中添加片段而不是替换片段?

20
我正在使用导航控件(Android Architecture)。我使用了一些示例来创建导航架构。但是问题在于,每次都会重新调用片段,就像从任何片段返回时替换片段一样。那么我该如何停止这个问题,并如何设置添加片段而不是替换片段的行为?
我在网上发现了这个问题,但没有人给我关于如何在导航控件中添加/替换片段的想法。我尝试使用片段ID来获取添加片段的方法,但没有成功。
以下是我的导航主机XML:我一遍又一遍地添加一个带有日志记录生命周期的片段。
<?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/nav_graph"
            app:startDestination="@id/questionanswer">

            <fragment
                android:id="@+id/questionanswer"
                android:name="com.softtech360.totalservey.fragment.QuestionAnswer"
                android:label="fragment_first"
                tools:layout="@layout/questionanswer" >
                <action
                    android:id="@+id/action_questionanswer_to_questionanswer"
                    app:destination="@id/questionanswer"

                    />
            </fragment>
</navigation>

我创建了一个按钮,每次触发函数时,使用它来交换主机片段上的碎片:
val navController = Navigation.findNavController(activity!!,R.id.navhost_fragment)
                            navController.navigate(R.id.questionanswer)
        // using this i swap the fragment on host fragment.

1
有找到任何解决方案吗? - NightFury
1
你实际遇到的问题是什么?如果你确实在保存状态,那么无论你使用add还是replace,你的fragment都将处于完全相同的状态。 - ianhanniballake
3个回答

0

尝试删除这一行

val navController = Navigation.findNavController(activity!!,R.id.navhost_fragment)
                        navController.navigate(R.id.questionanswer)

然后再次运行您的应用程序。


0

试试这个:

<action
    android:id="@+id/action_questionanswer_to_questionanswer"
    app:popUpTo="@+id/questionanswer"/>

替代

<action
    android:id="@+id/action_questionanswer_to_questionanswer"
    app:destination="@id/questionanswer"/>

然后:

navController.navigate(R.id.action_questionanswer_to_questionanswer)

发现这个链接

0
尝试一下,不要将目标更改为popUpTop。
navController.navigate(R.id.action_questionanswer_to_questionanswer)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接