在FragmentTransaction.commit()之后不会立即调用onCreateView() [英] onCreateView() isn't called immediately after FragmentTransaction.commit()

查看:908
本文介绍了在FragmentTransaction.commit()之后不会立即调用onCreateView()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态替换片段的活动:

I have an activity where I dynamically replace fragments:

private void goToFragment(Fragment newFragment, String tag) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment, tag);
    ft.addToBackStack(null);
    ft.commit();
}

现在,我想访问片段中的视图,以便我可以将数据(我已经存储在我的活动中),在调用 goToFragment 之后立即。

Now, I want to access the views inside the fragment so I can put data (that I have stored in my activity) into them, immediately after calling goToFragment.

问题是,片段的 onCreateView 在片段完全渲染之前不被调用,至少对我的理解。

The problem is, the fragment's onCreateView isn't called before the fragment is rendered completely, at least to my understanding.

我知道覆盖片段中的 onAttach(活动活动)是一种方法,但是我必须将其专门用于我的活动 - 我只是想避免因为我认为片段依赖于特定活动是不好的做法。

I know overriding the onAttach(Activity activity) in the fragment is one way to go about it, but then I have to cast it specifically to my activity - and I just want to avoid that because I consider it bad practice for the fragment to be dependent on a specific activity.

据我所见, Fragment 没有任何听众(作为主题)实现。

As far as I can see, Fragment doesn't have any listeners (as a subject) implemented.

所以我想我必须让自己的听众(使用观察者模式使片段成为主题和t他活动一个观察者),然后每当 onCreateView onAttach 完成时调用它,然后最后回调具有需要设置的数据的片段。然而,我需要为几个片段做这个,所以我必须为每个片段做一个监听器,我再次认为是坏的。

So I figure I have to make my own listener (Using the Observer Pattern to make the fragment a subject and the activity an observer), and then calling it whenever the onCreateView or onAttach is done, and then finally calling back to the fragment with the data that needs to be set. However, I need to do this for several fragments so I would have to make a listener for each fragment, which I again think is bad.

有没有更好/更容易方式这样做?

Is there any better/easier way to do this?

推荐答案

FragmentTransaction 调用 commit()。您可以手动强制更新:

FragmentTransaction isn't applied instantly after calling commit(). You may force update manually:

...
mFragmentManager.executePendingTransactions();

AFAIK事件回调的目的是与片段超出它通常的生命周期。

AFAIK event callbacks' purpose is custom communication with Fragment beyond it's usual lifecycle.

这篇关于在FragmentTransaction.commit()之后不会立即调用onCreateView()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆