是否有可能在活动的onCreate()内部引用Fragment的子视图?

时间:2016-04-08 21:27:17

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

我可以使用@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; } 来获取对片段中的子视图的引用,然后在该视图的同一片段内编写一个getter方法,该方法将调用该方法来获取对该视图的引用。视图。像:

onCreate()

但问题是我需要在Activity onCreateView()中查看子视图,我认为片段的onCreate()在{{1}之后被调用Activity返回。 Reference

那么有没有办法在活动的onCreate()内获得对片段视图的引用?

1 个答案:

答案 0 :(得分:-1)

手动调用onCreateView()应该可行,但这不是一个好方法。

private JavaCameraView javaCameraView;

@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(LayoutInflater layoutInflater) {
    if (javaCameraView == null) {
        onCreateView(layoutInflater, null, null);
    }
    return javaCameraView;
}

然后,您可以在yourFragment.getCameraView(getLayoutInflater())中使用onCreate()