返回按钮关闭应用程序,即使使用FragmentTransaction.addToBackStack时() [英] Back button closing app even when using FragmentTransaction.addToBackStack()

查看:439
本文介绍了返回按钮关闭应用程序,即使使用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??????????

推荐答案

您必须添加<一href="http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack%28java.lang.String,%20int%29"><$c$c>popBackStack()打电话到<一个href="http://developer.android.com/reference/android/app/Activity.html#onBack$p$pssed%28%29"><$c$c>onBack$p$pssed()活性的方法。

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();
    }
}

这篇关于返回按钮关闭应用程序,即使使用FragmentTransaction.addToBackStack时()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆