导航到 Android 中的另一个片段后如何清除导航堆栈 [英] How to clear navigation Stack after navigating to another fragment in Android
问题描述
我正在使用新的导航架构组件 在 android 中,在移动到新片段后,我一直在清除导航堆栈.
I am using The new Navigation Architecture Component in android and I am stuck in clearing the navigation stack after moving to a new fragment.
示例:我在 loginFragment 中,我希望在导航到 home 片段时从堆栈中清除此片段,以便用户在按下后退按钮时不会返回到 loginFragment.
Example: I am in the loginFragment and I want this fragment to be cleared from the stack when I navigate to the home fragment so that the user will not be returned back to the loginFragment when he presses the back button.
我正在使用一个简单的 NavHostFragment.findNavController(Fragment).navigate(R.id.homeFragment) 进行导航.
I am using a simple NavHostFragment.findNavController(Fragment).navigate(R.id.homeFragment) to navigate.
当前代码:
mAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.homeFragment);
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
我尝试使用 NavOptions 在 navigate(),但后退按钮仍然让我回到 loginFragment
I tried using the NavOptions in the navigate(), but the back button is still sending me back to the loginFragment
NavOptions.Builder navBuilder = new NavOptions.Builder();
NavOptions navOptions = navBuilder.setPopUpTo(R.id.homeFragment, false).build();
NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.homeFragment, null, navOptions);
推荐答案
首先,添加属性 app:popUpTo='your_nav_graph_id'
和 app:popUpToInclusive="true"
到操作标签.
First, add attributes app:popUpTo='your_nav_graph_id'
and app:popUpToInclusive="true"
to the action tag.
<fragment
android:id="@+id/signInFragment"
android:name="com.glee.incog2.android.fragment.SignInFragment"
android:label="fragment_sign_in"
tools:layout="@layout/fragment_sign_in" >
<action
android:id="@+id/action_signInFragment_to_usersFragment"
app:destination="@id/usersFragment"
app:launchSingleTop="true"
app:popUpTo="@+id/main_nav_graph"
app:popUpToInclusive="true" />
</fragment>
第二,导航到目的地,使用上述动作作为参数.
Second, navigate to the destination, using above action as parameter.
findNavController(fragment).navigate(
SignInFragmentDirections.actionSignInFragmentToUserNameFragment())
有关详细信息,请参阅文档.
See the docs for more information.
注意:如果您使用方法 navigate(@IdRes int resId)
进行导航,您将不会得到想要的结果.因此,我使用了方法 navigate(@NonNull NavDirections Directions)
.
NOTE: If you navigate using method navigate(@IdRes int resId)
, you won't get the desired result. Hence, I used method navigate(@NonNull NavDirections directions)
.
这篇关于导航到 Android 中的另一个片段后如何清除导航堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!