android - 我怎么知道 onCreateView 已经从外部类调用了?

标签 android android-fragments android-activity android-lifecycle

我真的很好奇如何确定(从外部类) fragment 是否为 onCreateView()已经被调用了。我搜索过类似的问题,但没有找到。

例如,是fragment.isAdded()一个好的指标?

我的第一个想法很简单 fragment.getView() != null ,但我并不是 100% 确定它看起来是否可靠,而且我也有点不愿意使用它(没有特别的原因,我只是倾向于避免无效检查)。我很乐意找到解决方法。我的建议:

已添加()

Return true if the fragment is currently added to its activity.

在我看来,这条线很含糊; 添加 不是附加,但也不是创建。可能是指FragmentTransaction.add() (这在语义上是错误的,因为您可以将 <fragment> 卡在您的布局中,而不必调用 addreplace)。

仍然,FragmentTransaction.add() documentation不提供任何信息,也不会让您思考 added -> created .我会说不。

isVisible()

Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.

看起来不错,从某种意义上说 isVisible() -> isCreated , 但第三个选项使它成为 isCreated != isVisible .我只是想到 View 分页器中的 fragment :并非所有 fragment 都是可见的,但是当前可见 fragment 附近的 fragment 被添加、创建并处于 Activity 状态,您可以调用它们的方法。但对他们来说,isVisible() == false .这有点太严格了。

isInLayout()

Return true if the layout is included as part of an activity view hierarchy via the < fragment> tag. This will always be true when fragments are created through the < fragment> tag, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.

我认为这在这里不适用。

getView() != null

Returns The fragment's root view, or null if it has no layout.

这看起来仍然是唯一的解决方案。我只想确认一下。

实现回调

..被称为onCreateView()或者,更好的是 onViewCreated() .但是:

  • 我不需要在 fragment 创建后立即调用某些东西(你为什么需要那个?),我需要在给定时间检查一些东西;
  • 应该定义相反的定义,例如 onViewNotAvailableAnymore(),以使检查始终有意义;
  • 我看不出这与 getView != null 有何不同或更好.

最佳答案

Does Fragment.isAdded() imply that onCreateView has been called?

!! !! 暂停 NOOOOOOO00000000000!!!!!

先生

Fragment.isAdded() 是一个通知,表明您的 Fragment 已添加到您的 Activity,故事结束。

FragmentTransaction中的add()方法有3个不同的方法,都是将Fragment添加到一个Activity中,并且,两个进一步创建您的 FragmentView 并借助于将其附加到 Parent ViewGroup LayoutInflater 如果您的第一个参数不是0 (id != 0)

要检查 onCreateView() 是否已被调用,您需要覆盖 onViewCreated()

getView() 将始终返回 null,除非 onCreateView() 完成

您的解决方案是检查 Fragment.isVisible()

仅供引用:我在文档中看到的没有任何问题。很清楚,先生。

希望我是清醒的先生

关于android - 我怎么知道 onCreateView 已经从外部类调用了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32658271/

相关文章:

Android 如何在 Activity 返回堆栈 "jump to another branch"中返回 "tree"?

android - android 中的 java.lang.UnsatisfiedLinkError 错误

java - 创建它的 Activity 被销毁后,Android 线程会发生什么?

android - ionic Cordova 运行Android给出gradle错误

android - Python 失去 Mysql 服务器连接

java - 我无法使用 fragment 从我的 Activity 访问 fragment 布局内的 TextView

android - ViewPager 不显示 fragment

android - 如何在 Android 中识别 MICR 码

java - 读取android :scheme programmatically的值

android - 单击 fragment 中的后退按钮后应用程序关闭