Android片段回按无任何数据丢失

Ams*_*eer 1 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();
Run Code Online (Sandbox Code Playgroud)

简而言之::每次回按我都想加载上一个片段而不重新创建它

May*_*val 5

我认为这可能会有所帮助

只是做PopBackStackFragmentmanager

FragmentManager fm = getFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
            fm.popBackStack();
        }
Run Code Online (Sandbox Code Playgroud)

在那个片段中

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;
    }
Run Code Online (Sandbox Code Playgroud)