Android(Fragment) - Is it recommended to initialize a view object inside onActivityCreated method?

夙愿已清 提交于 2019-12-06 03:03:12
textView = (TextView) getActivity().findViewById(R.id.text_view);

This will try to find the view with id R.id.text_view from the layout of your activity, not your fragment. If the view with that id is present in your fragment itself then you should use the onCreateView method within your fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmant_two,container,false);
    TextView textView = (TextView) view.findViewById(R.id.text_view);
    // bind your data here.
    return view;
}

Obviously onActivityCreated was used because the view is found on the Activity.

You could also use onAttach for that, though.

Personally, onViewCreated is where I put my Fragment view initializations

onCreateView(): You can assign your View variables and do any graphical initialisations here.

onActivityCreated(): It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements).

Khoa Tran

You can refer to this question to understand more about onActivityCreated and onCreateView here

onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView(). In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!