android - 是否可以在 Activity 的 onCreate() 中获取对 Fragment subview 的引用?

标签 android android-fragments android-activity android-fragmentactivity oncreate

我可以使用 onCreateView() 获取 fragment 中 subview 的引用,然后在同一 fragment 内为该 View 编写一个 getter 方法,该方法将由 Activity 调用以获取对 View 的引用。喜欢:

@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
    LinearLayout rootLinearLayout = (LinearLayout) layoutInflater.inflate(R.layout.my_fragment, container, false);
    javaCameraView = (JavaCameraView) rootLinearLayout.findViewById(R.id.myFragment_javaCameraView);//***********
    return rootLinearLayout;
}

JavaCameraView getCameraView() {
    return javaCameraView;
}

但问题是我需要Activity的onCreate()里面的 subview ,我认为 fragment 的onCreateView()是在 Activity 返回的 onCreate() 之后调用。 Reference

那么有没有办法在 Activity 的 onCreate() 中获取对 fragment View 的引用?

最佳答案

你做错了。您不应将 fragment 的 UI 元素暴露给托管 Activity 。 fragment 应该封装它的 View 和功能。如果您真的只是将 fragment 用作 UI 组件,请创建自定义 View 并在 Activity 中使用它。

要回答您的问题,不,您无法在 Activity 的 onCreate() 中获得对 fragment View 的引用。原因是 fragment 的 View 在 fragment 经历其生命周期之前不存在。无法保证这种情况何时会发生,这就是为什么基于此类假设进行编码是不好的。

如果 fragment 需要将事件传回 Activity ,请让您的 Activity 实现监听器接口(interface),并让 fragment 在适当的时候调用该接口(interface)。

因此在您的情况下,您可以在 fragment 的 onCreateView() 中执行类似的操作,

if (getActivity() instanceof Listener) {
  ((Listener)getActivity()).onViewCreated(fragmentViews);
}

但同样,这样做是错误的。

关于android - 是否可以在 Activity 的 onCreate() 中获取对 Fragment subview 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36509618/

相关文章:

java - ExoPlayer - 播放 SD 卡中的本地 mp4 文件

android - 避免 IllegalStateException “Can not perform this action after onSaveInstanceState"

java - android.view.InflateException 膨胀类 fragment 时出错

java - 谷歌分析平均 session 持续时间为 00 :00:00

java - Android - Activity 在无限循环中重新启动

android checkbox onCheckedChanged 没有被调用

java - 在android源码中找不到自己创建的文件路径

javascript - 'setRemoteDescription'上执行 'RTCPeerConnection'失败 : Failed to set remote answer sdp

android - 将触摸事件从对话框 fragment 传递到下方的 View (在父 Activity 内)

java - Android - fragment 启动但不显示内容