在FragmentTransaction.commit()之后不会立即调用onCreateView()

编程入门 行业动态 更新时间:2024-10-27 12:41:15
本文介绍了在FragmentTransactionmit()之后不会立即调用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); ftmit(); }

现在,我想访问片段中的视图,以便我可以将数据(我已经存储在我的活动中),在调用 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()

本文发布于:2023-10-26 21:42:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:FragmentTransaction   commit   onCreateView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!