Android的FragmentTransaction承诺什么时候?什么时候、Android、FragmentTransaction

2023-09-05 06:41:09 作者:扬尘浮若

我建立一个平板电脑应用程序。在这个程序中,多与两个片段一个活动。第一个片段是一个已知的名单片段是显示从数据库中查询一个简单的项目布局列表,第二个片段显示有关所选记录的详细信息(从列表中的片段)。的思考与第二片段是其类型取决于从记录被显示在列表中。例如,如果记录是顾客然后选定客户的细节被示出,如果它们是所选择的项目的详细信息显示库存物品等 为了与细节片段沟通我创建的每一个细节片段类实现一个接口。 在从布局的xml活动列表片段固定。细节片段不过是活动的创建这样的过程中创建的:

I am building a tablet app. In this app there is one activity with two fragments. First fragment is a "known" list fragment which is showing a simple one item layout list from a database query, the second fragment shows the details about the selected record (from the list fragment). The think with the second fragment is that its type depends from the records being showed in the list. For example if the records are customers then the selected customer's details are shown, if they are inventory items the selected item's details are shown etc. In order to communicate with the Details Fragment I 've created an interface which every detail fragment class implements. The list fragment is "fixed" in the activity from the layout xml. The detail fragment however is created during the activity's creation like this:

super.onCreate(savedInstanceState);
setContentView(R.layout.act_hlpfiles_host);

.....

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.laydetailsfragment, FragmentsPool.getHelperFileFragment(501), "recordDetails");
fragmentTransaction.commit();

myDetailsFragment = getFragmentManager().findFragmentByTag("recordDetails");

...

myListFragment = (frg_hlpfiles_lstrecords) getFragmentManager().findFragmentById(R.id.frg_lstrecords);

....
}

本code的问题是,myDetailsFragment总是空。这是因为fragmentTransaction.commit()不立即运行,但下一次线程准备它发生在主线程(如android的文档状态)。

The problem with this code is that myDetailsFragment is always null. This is because the fragmentTransaction.commit() does not run immediately but it happens on the main thread the next time that thread is ready (as the android documentation states).

如果我创建ONSTART(细节片段)和实例化的onCreate一切列表片段工作正常。

If I create the detail fragment in onStart() and instantiate the list fragment in onCreate everything works ok.

所以,问题是:我怎么能肯定的是,fragmentTransaction.commit()已提交事务,所以我可以做一些工作,增加的片段?此外,有没有办法等到提交情况,然后继续的code中的其他人呢?

So the question is: How can I be sure that the fragmentTransaction.commit() has commit the transaction so I can do some work with the added fragment? Furthermore is there any way to wait until the commit happens and then continue with the rest of the code?

感谢您的时间和精力,

克里斯托

推荐答案

尝试运行fragmentManager.executePendingTransactions()提交你的事务之后,但按标签查找,看是否适合你。

Try running fragmentManager.executePendingTransactions() after committing your transaction but before finding by tag and see if that works for you.