addToBackStack()不起作用

时间:2015-01-25 03:07:18

标签: android android-fragments

我的MainActivity管理两个一起工作的片段。 我的一个方法是ListFragment上的监听器接口,MainActivity负责切换片段。

但由于某些原因,似乎addToBackStack不起作用。当我点击列表时,转到下一个片段,然后点击设备的后退按钮......它就在设备主屏幕上的应用程序之外。

任何人都知道这是什么问题?

@Override
public void OnSelectionChanged(Object object) {
    DetailFragment DetailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);

    if (DetailFragment != null) {
        DetailFragment.setTitle(object);
    } else {
        DetailFragment newDetailFragment = new DetailFragment();
        Bundle args = new Bundle();

        args.putSerializable(DetailFragment.KEY_POSITION,object);
        newDetailFragment.setArguments(args);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

        fragmentTransaction.replace(R.id.fragment_container, newDetailFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

2 个答案:

答案 0 :(得分:3)

您应该在MainActivity中添加此方法。

@Override
public void onBackPressed() {
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        fm.popBackStack();
    } else {
        super.onBackPressed();
    }
}

并检查您的导入以使用android.app.而不是android.support.v4.app.

例如:

import android.app.FragmentManager;

而不是:

import android.support.v4.app.FragmentManager;

答案 1 :(得分:1)

If you are using extends AppCompatActivity in your activity go ahead and use the imports from the support library.

import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction;

then change your calls from

getFragmentManager();

to

getSupportFragmentManager();

This should work fine. As I just had to fix this in one of my projects as well. I learned about this here https://teamtreehouse.com/library/android-fragments/managing-fragments/managing-the-back-stack

However it's a paid online learning solution so I am unsure if you'll be able to see it. They occasionally have some videos open to the public.

If you are using extends Activity and want to continue using getFragmentManager();

then you'll want to use

import android.app.FragmentManager;

You should need to have to override the onBackPressed() method. While it does work in these cases it's more of a hack than a solution.