一、FramentManager.findFragmentByTag() returns null
getFragmentManager().beginTransaction()
.replace(R.id.graph_fragment_holder, new GraphFragment(), "GRAPH_FRAGMENT")
.commit();
//getFragmentManager().executePendingTransactions();
GraphFragment graphFragment = (GraphFragment)getFragmentManager()
.findFragmentByTag("GRAPH_FRAGMENT");
graphFragment.setData(data); // error graphFragment is null
代码如上所示,结果获取到的graphFragment 为null,这下子百思不得其解。最后发现FragmentTransaction提交一个新的fragment会先将该fragment加入到主线程队列。所以立刻去获取findFragmentByTag,返回的是null。
解决方案是在commit后,添加 getFragmentManager().executePendingTransactions(); 官方注释如下,会立刻执行。
public abstract boolean executePendingTransactions ()
Added in API level 11
After a FragmentTransaction is committed with FragmentTransaction.commit(),
it is scheduled to be executed asynchronously on the process's main thread.
If you want to immediately executing any such pending operations,
you can call this function (only from the main thread) to do so.
Note that all callbacks and other related behavior will be done from within this call,
so be careful about where this is called from.
Returns
Returns true if there were any pending transactions to be executed.