导航抽屉后退按钮到主要片段 [英] Navigation drawer back button to primary fragment
问题描述
阅读此之后并在Android文档中进行搜索,我放弃了,并决定在这里询问.我试图在我的 Navigation Drawer
中设置一个后退按钮,以便该应用仅从 Home
片段关闭,而其他任何片段都将使我们回到首页
.例如,如果我们从 Home
片段开始并导航到导航抽屉中的其他片段,则单击后退"按钮时,将进入 Home
片段,如果我们单击从Home片段返回,我们将退出该应用程序.
After reading this and searching in Android documentation, I gave up and decided to ask here.
I'm trying to set a back button in my Navigation Drawer
so that the app will close only from the Home
fragment, and any other fragment will take us back to Home
. For example, if we begin at Home
fragment and navigate to other fragments in the navigation drawer, when we hit the back button we will get to Home
fragment, and if we hit back from Home fragment, we will exit the app.
我试图像这样实现它:
public void onNavigationDrawerItemSelected(int position) {
...
// If the next fragment is Home, clear the backstack.
if (frag instanceof Home) {
getSupportFragmentManager().popBackStack();
fragmentManager.beginTransaction().replace(R.id.container, frag)
.commit();
}
// If the backstack already contains a transaction, replace the current fragment
else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
fragmentManager.beginTransaction().replace(R.id.container, frag)
.commit();
}
// If the backstack is empty, insert the Home -> Fragment transaction
else {
fragmentManager.beginTransaction().replace(R.id.container, frag)
.addToBackStack("").commit();
}
...
}
...
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.LEFT);
} else {
super.onBackPressed();
// If returning back to Home fragment, restore action bar title.
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onSectionAttached(0);
}
}
我附加的链接无法正常工作,并且我实现的方式不一致.例如,如果我从首页"导航到其他片段,然后返回首页(无需按后退"按钮),则我的片段会彼此重叠.
The link I have attached is not working properly, and the way I implemented is not working consistently. For example, if I navigate from Home to other fragments and back to home (without pressing the back button), my fragments get overlay one another.
推荐答案
我刚刚找到了一种使这项工作相当容易的方法,所以我决定将其发布在这里:
I just found a way to make this work fairly easy, so I decided to post it here:
// Are we in Home fragment?
private boolean homeFrag = true;
...
@Override
public void onNavigationDrawerItemSelected(int position) {
...
// Next fragment is Home?
if (frag instanceof Home)
homeFrag = true;
else
homeFrag = false;
fragmentManager.beginTransaction().replace(R.id.container, frag)
.commit();
onSectionAttached(position);
}
...
@Override
public void onBackPressed() {
// Close navigation drawer if open
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.LEFT);
} else {
// If not in Home, move back to Home.
if (!homeFrag) {
onNavigationDrawerItemSelected(0);
} else
super.onBackPressed();
}
}
我想听听您对这个解决方案的想法.
I would like to hear your thoughts about this solution.
这篇关于导航抽屉后退按钮到主要片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!