更新:
如果您有这样的导航图:
android:id="@+id/firstFragment"
android:name="com.appname.package.FirstFragment" >
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment" />
android:id="@+id/secondFragment"
android:name="com.appname.package.SecondFragment"/>
并且您希望导航到第二个片段并使其成为图形的根,指定下一个NavOptions:
NavOptions navOptions = new NavOptions.Builder()
.setPopUpTo(R.id.firstFragment, true)
.build();
并使用它们进行导航:
Navigation.findNavController(view).navigate(R.id.action_firstFragment_to_secondFragment, bundle, navOptions);
setPopUpTo(int destinationId, boolean inclusive) – Pop up to a given destination before navigating. This pops all non-matching destinations from the back stack until this destination is found.
destinationId – The destination to pop up to, clearing all intervening destinations.
inclusive – true to also pop the given destination from the back stack.
替代方案:
android:id="@+id/firstFragment"
android:name="com.appname.package.FirstFragment" >
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment"
app:popUpTo="@+id/firstFragment"
app:popUpToInclusive="true" />
android:id="@+id/secondFragment"
android:name="com.appname.package.SecondFragment"/>
然后在你的代码上:
findNavController(fragment).navigate(
FirstFragmentDirections.actionFirstFragmentToSecondFragment())
老答案
不推荐使用:已弃用动作的clearTask属性和NavOptions中的关联API.
如果要将根片段更改为片段2(例如,在片段2上按下后退按钮后将退出应用程序),则应将下一个属性添加到您的操作或目标:
app:clearTask="true"
实际上它看起来是另一种方式:
android:id="@+id/firstFragment"
android:name="com.appname.package.FirstFragment"
android:label="fragment_first" >
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment"
app:clearTask="true" />
android:id="@+id/secondFragment"
android:name="com.appname.package.SecondFragment"
android:label="fragment_second"/>
我添加了app:clearTask =“true”来执行操作.
现在,当您执行从片段1到片段2的导航时,请使用下一个代码:
Navigation.findNavController(view)
.navigate(R.id.action_firstFragment_to_secondFragment);