[英]Android navigation architecture component - system's back button exits the app
I am making a demo using android's navigation architecture component .我正在使用 android 的导航架构组件制作一个演示。 I have an
activity
and two fragments
.我有一个
activity
和两个fragments
。
In the activity's xml, I have added the following code-在活动的 xml 中,我添加了以下代码-
<fragment
android:id="@+id/main_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="@dimen/match_constraints"
android:layout_height="@dimen/match_constraints"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_graph" />
And then I have set the first fragment as the start destination.然后我将第一个片段设置为起始目的地。 In the first fragment, on a button's click I have done following -
在第一个片段中,在单击按钮时,我完成了以下操作 -
NavHostFragment.findNavController(this).navigate(R.id.action_firstFragment_to_secondFragment)
And it works fine.它工作正常。 Now when I press system's back button, ideally I should go back to first fragment, but the app exits.
现在当我按下系统的后退按钮时,理想情况下我应该回到第一个片段,但应用程序退出。 What am I doing wrong?
我究竟做错了什么?
I suppose, this is occurring in your code just because you might be handling the onBackPressed()
functionality somewhere in your BaseActivity
.我想,这是发生在你的代码,因为你可能会被处理
onBackPressed()
在功能某处BaseActivity
。 Please look carefully.请仔细看。
I hope, this helps you.我希望这可以帮助你。
/** orrerride activity onBackPressed() **/
private boolean doubleBackToExitPressedOnce = false;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onBackPressed() {
int start = Navigation.findNavController(this, R.id.nav_host_fragment).getCurrentDestination().getId();
if (start == R.id.nav_home) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(MainActivity.this, "Press back again to exits", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.