【发布时间】:2021-08-04 09:37:13
【问题描述】:
在我的应用中,我有 fragment_1、fragment_2 和 activity_2。所以我的主导航有这两个片段。从片段 1 我可以导航到片段 2,从片段 2 我可以导航到活动 2。当我从片段 2 导航到活动 2 时,我必须弹出这个片段。
这是我的导航文件代码。
<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/firstFragment">
<fragment
android:id="@+id/firstFragment"
android:name="com.example.navcomponentbug.FirstFragment"
android:label="fragment_first"
tools:layout="@layout/fragment_first">
<action
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment" />
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.example.navcomponentbug.SecondFragment"
android:label="fragment_second"
tools:layout="@layout/fragment_second">
<action
android:id="@+id/action_secondFragment_to_secondActivity"
app:destination="@id/secondActivity"
app:popUpTo="@id/firstFragment"
app:popUpToInclusive="true"/>
</fragment>
<activity
android:id="@+id/secondActivity"
android:name="com.example.navcomponentbug.SecondActivity"
android:label="activity_second"
tools:layout="@layout/activity_second" />
</navigation>
很简单,对吧? 所以这是第一个片段中的导航:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btn: Button = view.findViewById(R.id.btn_navigate_to_second_fragment)
btn.setOnClickListener {
findNavController().navigate(R.id.action_firstFragment_to_secondFragment)
}
}
那么相同的代码用于第二个片段,它导航到活动,只是动作不同(不想粘贴相同的代码)。
还有我的活动 2 的代码:
binding.btnNavigateToFirstFragment.setOnClickListener {
finish()
}
似乎一切都很好,但没有。当我从活动 2 导航回第一个片段,然后再次单击按钮导航到第二个片段时,我收到此错误
java.lang.IllegalArgumentException: Navigation action/destination com.example.navcomponentbug:id/action_firstFragment_to_secondFragment cannot be found from the current destination NavGraph(com.example.navcomponentbug:id/main_navigation) startDestination={Destination(com.example.navcomponentbug:id/firstFragment) label=fragment_first class=com.example.navcomponentbug.FirstFragment}
那么为什么会这样呢?谢谢。
【问题讨论】:
标签: android kotlin android-jetpack-navigation