上面的标题已经被问了很多,但答案似乎与 FragmentStatePagerAdapter
密切相关,这与我的问题无关。我直接使用 putFragment(Bundle, String, Fragment)
方法。
Android Documentation对于 putFragment(Bundle, String, Fragment)
说:
Put a reference to a fragment in a Bundle. This Bundle can be persisted as saved state, and when later restoring getFragment(Bundle, String) will return the current instance of the same fragment.
Parameters
* bundle The bundle in which to put the fragment reference.
* key The name of the entry in the bundle.
* fragment The Fragment whose reference is to be stored.
但是下面的代码会抛出一个异常:
Bundle bundle = new Bundle();
CustomFragment actionBarFragment = getActionBarFragment();
CustomFragment contentFragment = getContentFragment();
actionBarFragment.setArguments(bundle);
contentFragment.setArguments(bundle);
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mTransaction.add(R.id.actionBarPane, actionBarFragment);
mTransaction.add(R.id.contentPane, contentFragment);
mTransaction.commit();
getSupportFragmentManager().putFragment(bundle, "ContentFragment", contentFragment);
getSupportFragmentManager().putFragment(bundle, "ActionBar", actionBarFragment);
我使用上面的原因是 ContentFragment 和 ActionBar fragment 都可以使用 getArguments()
的结果来找到它们相反的数字,即使它们当前不在顶部backstack 的 - 例如如果它们被堆栈中更高的透明 Fragments 部分遮挡。
但是,我得到了异常:
11-20 13:44:17.842: E/Default Exception Handler(12466): Caused by: java.lang.IllegalStateException: Fragment CustomFragment{4219bdb8 id=0x7f06002e com.test.CustomFragment1} is not currently in the FragmentManager
我能否由此得出结论,commit()
只是将事务放在堆栈上以在 UI 线程上完成,而 putFragment()
调用在此之前发生交易正在进行中?还是我误会了什么? (Android 网站上的文档没有说明任何关于 fragment 的先决条件状态,我认为它应该处于这种状态)。
值得注意 commit()
中的文本,这就是为什么我认为调用发生得太早的原因 - 一个可能的答案是如何将监听器附加到事务以在事务发生时通知您commit()
编辑。我只是认为那不存在...
Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
编辑
通过使用糟糕的解决方案确认 commit()
是问题所在:
mTransaction.commit();
new Thread() {
public void run() {
while(!contentFragment.isAdded()) {
try {
Thread.sleep(100);
} catch (Exception e) {}
}
getSupportFragmentManager().putFragment(bundle, "ContentFragment", contentFragment);
getSupportFragmentManager().putFragment(bundle, "ActionBar", actionBarFragment);
};
}.start();
真正的解决方案仍然非常受欢迎。
最佳答案
我自己没用过,但是你看过FragmentManager.executePendingTransactions()吗? ?文档是这样说的:
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.
听起来它符合您的用例。
关于android - putFragment() - fragment x 当前不在 FragmentManager 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041508/