android – popBackStack导致一次又一次调用片段的oncreateView

前端之家收集整理的这篇文章主要介绍了android – popBackStack导致一次又一次调用片段的oncreateView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有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方法,你应该适当地处理它

原文链接:https://www.f2er.com/android/315237.html

猜你在找的Android相关文章