Gra*_*eme 5 android android-fragments fragment-backstack
上面的标题已经被问了很多次,但答案似乎FragmentStatePagerAdapter与我的问题无关。我putFragment(Bundle, String, Fragment)直接用这个方法。
Android文档说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.
Run Code Online (Sandbox Code Playgroud)
但是下面的代码会抛出异常:
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);
Run Code Online (Sandbox Code Playgroud)
我使用上述内容的原因是,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
Run Code Online (Sandbox Code Playgroud)
我是否可以由此得出结论,commit()只需将事务放在要在 UI 线程上完成的堆栈上,并且putFragment()调用是在执行该事务之前发生的?或者我误解了什么?(Android 网站上的文档没有说明任何关于片段的先决条件状态,我认为它应该处于其中)。
值得注意的是,其中的文本commit()是我认为调用发生得太早的原因 - 一个可能的答案是如何将侦听器附加到事务以在事务被commit()编辑时通知您。我只是认为不存在...
安排此事务的提交。提交不会立即发生;它将被安排为主线程上的工作,以便在下次该线程准备好时完成。
编辑
通过使用一个糟糕的解决方案确认这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();
Run Code Online (Sandbox Code Playgroud)
真正的解决方案仍然非常受欢迎。
我自己从未使用过它,但是您看过FragmentManager.executePendingTransactions()吗?文档是这样说的:
使用 FragmentTransaction.commit() 提交 FragmentTransaction 后,它被安排在进程的主线程上异步执行。如果您想立即执行任何此类挂起的操作,您可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意调用此函数的位置。
听起来它符合您的用例。
| 归档时间: |
|
| 查看次数: |
2335 次 |
| 最近记录: |