我有3个片段A,B,C.我写了一段代码来替换它们并维护backstack:
public void addFragment(Fragment fragmentToAdd,String fragmentTag) { FragmentManager supportFragmentManager = getSupportFragmentManager(); Fragment activeFragment = getActiveFragment(); FragmentTransaction fragmentTransaction = supportFragmentManager .beginTransaction(); if (null != activeFragment) { fragmentTransaction.hide(activeFragment); } fragmentTransaction.replace(R.id.layout_child_activity,fragmentToAdd,fragmentTag); if (supportFragmentManager.getBackStackEntryCount() > 1) { supportFragmentManager.popBackStack(); } fragmentTransaction.addToBackStack(fragmentTag); fragmentTransaction.commit(); }
在这段代码中
if (supportFragmentManager.getBackStackEntryCount() > 1) { supportFragmentManager.popBackStack(); }
如果堆栈长度大于1,我使用pop来获取最新的片段.现在由于这个,当长度大于1时,它会一次又一次地调用onCreate视图.
喜欢 :
>打开A.
>开放B.
>打开C.(如果打开C. onCreateView的A被调用.)
解决方法
正如文档所说,正如行为是正常的,来自后台交易. Backstack,从不保存Fragments,它只是保存事务
http://developer.android.com/intl/es/guide/components/fragments.html
我做了什么,我不确定它是否是最好的方式,但是
当我想清除我做的所有交易
1)在您的活动中检查后堆栈中是否有任何交易,
并在你的片段中添加一个标志,在你的情况下是A.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount(); if(backStackCount > 0) { Transactions.MUST_DETACH_FROM_BACKSTACK = true; getSupportFragmentManager().popBackStackImmediate(null,FragmentManager.POP_BACK_STACK_INCLUSIVE); }
2)在你的片段A里面,获取标志并删除fragent onCreateView并像这样返回null
public class Transactions extends android.support.v4.app.Fragment{ public static boolean MUST_DETACH_FROM_BACKSTACK = false; public Transactions() { // required empty public constructor } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { Log.i("FRAGMENT","onCreateView "+MUST_DETACH_FROM_BACKSTACK); // Inflate the layout for this fragment if (MUST_DETACH_FROM_BACKSTACK) { MUST_DETACH_FROM_BACKSTACK = false; getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); return null; } return inflater.inflate(R.layout.fragment_transactions,container,false); } @Override public void onViewCreated(View view,Bundle savedInstanceState) { super.onViewCreated(view,savedInstanceState); Log.i("FRAGMENT","onViewCreated"); if(view != null){ Log.i("FRAGMENT","ThreadStarted"); startThread(view); } }
但要小心我得到onResume()之后调用
OnCreateView()
即使使用getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
因此,如果你有任何conde onResume方法,你应该适当地处理它