我之前发现了类似的问题并尝试了一些;但不适合我。
我有一个主要活动,在布局中有一个片段容器。我有3个片段将根据导航抽屉选择被片段容器替换。我正在将所有交易添加到后台。
我想将Tracker片段的活动设置为主屏幕,这样当用户按下后退按钮时,他应该转到第一个片段。如果他已经在第一个片段,应用程序应该退出。
这是我的代码:
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
fragmentManager = getFragmentManager();
Fragment fragment;
switch (position){
case 0:
fragment = TrackerFragment.newInstance(position);
break;
case 1:
fragment = CalendarViewFragment.newInstance(position);
break;
case 2:
fragment = SettingsFragment.newInstance(position);
break;
default:
fragment = TrackerFragment.newInstance(position);
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).addToBackStack(null)
.commit();
}
我不知道如何在OnBackPressed方法上处理这个场景。我应该做什么逻辑。有没有任何方法可以做到这一点而不添加到后台堆栈? 任何帮助真的很感激! Thanks1
答案 0 :(得分:2)
private int mCurrentFragmentPosition;
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
mCurrentFragmentPosition = position;
fragmentManager = getFragmentManager();
Fragment fragment;
switch (position){
case 0:
fragment = TrackerFragment.newInstance(position);
break;
case 1:
fragment = CalendarViewFragment.newInstance(position);
break;
case 2:
fragment = SettingsFragment.newInstance(position);
break;
default:
fragment = TrackerFragment.newInstance(position);
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
@Override
public void onBackPressed() {
if(mCurrentFragmentPosition != 0){
onNavigationDrawerItemSelected(0);
}
else {
finish();
}
}