返回按钮关闭应用程序,即使使用FragmentTransaction.addToBackStack时()
无我已经阅读计算器上的其他问题已经能够帮助我的问题。据我所知道的,我是在做正确的一切。
None of the other questions I have read on stackoverflow have been able to help with my problem. As far as I can tell, I am doing everything correctly.
我有一个片段一个主/详细流程。
I have a master/detail flow with fragments.
在创建时的主要活动中,主片段装有下列code:
Upon creation of the main activity, the master fragment is loaded with the following code:
Fragment frag;
frag = new MainListFragment();//<-- **the master fragment**
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.fragment_container, frag);
Log.d("My Debug Bitches", "stack:" + fm.getBackStackEntryCount());
transaction.commit();
主片段有一个的ListView
;点击一个列表项目带来了细节片段,像这样:
The master fragment has a ListView
; clicking on a list item brings up the details fragment like so:
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
SubListFragment frag = new SubListFragment();//<-- **the detail fragment**
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
fm.executePendingTransactions();
Log.d("My Debug Bitches", "stack:" + fm.getBackStackEntryCount());
}
现在,根据LogCat中,在 BackStackEntryCount
从0变为1 后,我从主片段导航细节片段:
Now, according to LogCat, the BackStackEntryCount
changes from 0 to 1 after I navigate from master fragment to detail fragment:
那么,为什么,当我点击后退按钮,同时在细节的片段,该应用程序关闭,而不是返回到主片段??????????
So why is it that, when I click the back button while in the details fragment, that the app closes instead of returning to the master fragment??????????
您必须添加popBackStack()$c$c>打电话到onBack$p$pssed()$c$c>活性的方法。
You have to add the popBackStack()
call to the onBackPressed()
method of the activity.
例如:
@Override
public void onBackPressed() {
if(fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}