Search code examples
androidandroid-fragmentsandroid-activityandroid-fragmentactivityoncreate

Is it possible to get a reference to a Fragment's child View inside the onCreate() of Activity?


I could use onCreateView() to get a reference to a a child view in a fragment, and then write a getter method inside the same fragment for this view, which would be called by the Activity to get a reference to the view. Like:

@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;
}

But the problem is that I need the child view inside the Activity's onCreate(), and I think onCreateView() of fragment is called AFTER the onCreate() of Activity returns. Reference

So is there a way to get a reference to a fragment's view, inside the onCreate() of the Activity?


Solution

  • You are doing it wrong. You should not be exposing a fragment's UI elements to the hosting activity. A fragment should encapsulate it's views and functionality. If you are really only using the fragment as a UI component, create a custom View and use that in the activity.

    To answer your question, no, you can't get a reference to the fragment's view in the activity's onCreate(). The reason is that the fragment's view doesn't exist until the fragment has gone through it's lifecycle. There's no guarantee when that's going to happen, which is why it's bad to be coding based on such assumptions.

    If the fragment needs to communicate events back to the activity, have your activity implement a listener interface, and have the fragment call that interface when appropriate.

    So in your case, you could do something like this in the fragment's onCreateView(),

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

    But again, that's doing it wrong.