Android Honeycomb: How to determine when FragmentTrancaction.commit() has finished?

99封情书 提交于 2019-12-08 08:14:33

问题


I had this simple piece of code:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    //...

    NetworkWorker networkFragment = NetworkWorker.createInstance(null);
    fragmentTransaction.add(networkFragment, NETWORK);

    //...

    fragmentTransaction.commit();

    networkFragment.startURLRequest("test");
}

which crashed when I called getActivity() in my startURLRequest() routine.

As soon as I've moved the startURLRequest() call to onStart() it worked fine.

So I googled a bit and found this:

Calling commit() does not perform the transaction immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon as the thread is able to do so. If necessary, however, you may call executePendingTransactions() from your UI thread to immediately execute transactions submitted by commit(). Doing so is usually not necessary unless the transaction is a dependency for jobs in other threads. [AndDev guide]

Now, my question is... is it really advisable to use this executePendingTransactions() or will this hold some traps? Is there another way to determine if the transaction have finished? Just guessing that they might be finished in the Activity's next routine doesn't seem satisfying.

Kind regards, jellyfish


回答1:


Maybe you are thinking about this the wrong way. Rather than calling startURLRequest on your fragment from the activity why not call startURLRequest in your fragment's onAttach, onCreate etc. methods as at these points you know that the fragment is attached to the activity and getActivity() will succeed.

It does seem to me that the fragment should be deciding on when to call startURLRequest and not the activity. Otherwise from your activity would have to test to ensure the fragment is associated with a fragment.




回答2:


One would assume that the commit is finished when all fragments in the transaction have returned from onResume (for fragments being added).



来源:https://stackoverflow.com/questions/6276991/android-honeycomb-how-to-determine-when-fragmenttrancaction-commit-has-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!