putFragment() - 片段 x 当前不在 FragmentManager 中

2024-05-17

上面的标题被问了很多次,但答案似乎与FragmentStatePagerAdapter这与我的问题无关。我正在使用该方法putFragment(Bundle, String, Fragment)直接地。

The 安卓文档 http://developer.android.com/reference/android/app/FragmentManager.html#putFragment(android.os.Bundle,%20java.lang.String,%20android.app.Fragment) for putFragment(Bundle, String, Fragment) says:

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 片段都可以使用以下结果getArguments()找到它们相反的数字,即使它们当前不在返回堆栈的顶部 - 例如,如果它们被堆栈中较高的透明片段部分遮挡。

但是,我得到了例外:

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 网站上的文档没有说明任何关于片段的先决条件状态,我认为它应该处于其中)。

值得注意的是其中的文字commit()这就是为什么我认为调用发生得太早 - 一个可能的答案是如何将侦听器附加到事务以在事务发生时通知您commit()编辑。我只是认为不存在...

安排此事务的提交。提交不会立即发生;它将被安排为主线程上的工作,以便在下次该线程准备好时完成。

EDIT

确认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() http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions()?文档是这样说的:

提交 FragmentTransaction 后 FragmentTransaction.commit(),计划执行 在进程的主线程上异步执行。如果你想 立即执行任何此类挂起的操作,您可以调用它 函数(仅来自主线程)来执行此操作。请注意,所有回调 和其他相关行为将在此调用中完成,因此 小心从哪里调用它。

听起来它符合您的用例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

putFragment() - 片段 x 当前不在 FragmentManager 中 的相关文章

随机推荐