一、什么是回退栈
Activity切换时是通过栈的形式,不断压栈出栈.在Fragment的时候,如果你不是手动打开回退栈,它是直接销毁再重建.但如果将Fragment任务添加到回退栈,情况就不会一样了,它就有了累死Activity的栈管理方式.
二、回退栈的使用
fragment跳转的封装
public void startToFragment(Context context, int container, Fragment newFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(container, newFragment);
transaction.addToBackStack(context.getClass().getName());
transaction.commit();
}
fragment1 --> fragment2
Fragment2 fragment2 = new Fragment2 ();
startToFragment(getActivity(), R.id.layout_container, fragment2 );
fragment2 --> fragment1
getActivity().getFragmentManager().popBackStack();
fragment2 --> fragment3
Fragment3 fragment3 = new Fragment3 ();
startToFragment(getActivity(), R.id.layout_container, fragment3 );
fragment3 --> fragment1
//回退栈中某个Fragment之上的所有Fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate(
MainActivity.class.getName(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
网友评论