Android片段后退没有任何数据丢失

时间:2017-01-12 05:23:35

标签: android android-fragments

当我点击每个导航列表时,我正在创建一个带导航抽屉的应用程序。其中一个片段有listView。当我单击此列表时加载另一个片段。现在我使用导航抽屉移动到不同的片段。当我每次想要移动到上一个片段而没有任何数据更改时按下后退按钮。我该怎么办?

我使用以下代码加载片段:

FragmentManager fm = getFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
            fm.popBackStack();
        }
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
            fragmentTransaction.replace(R.id.fragmentHome, fr);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            fragmentTransaction.commit();

简而言之::每次背压我想加载以前的片段而不重新创建

2 个答案:

答案 0 :(得分:4)

我认为这可能会有所帮助

PopBackStack

执行Fragmentmanager
FragmentManager fm = getFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
            fm.popBackStack();
        }

并在那片段中

View mView ; //this will be global

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            if (mView == null) {
                // view will be initialize for the first time .. you can out condition for that if data is not null then do not initialize view again. 
                mView = inflater.inflate(R.layout.xml,container, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mView;
    }

答案 1 :(得分:0)

public  void addFragment( final Fragment newFragment, final Fragment hideFragment) {
    final FragmentManager fragmentManager = getFragmentManager();
    final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.hide(hideFragment);
    fragmentTransaction.add(R.id.container, newFragment, newFragment.getClass().getSimpleName());
    fragmentTransaction.addToBackStack(hideFragment.getClass().getSimpleName());
    fragmentTransaction.commitAllowingStateLoss();
}

使用此代替替换fragment.will解决您的问题。