I am really curious about what is the best practice to setup views in a Fragment. This is what I have been doing ever since I started developing for android.
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
ListView listView = view.findViewById(...);
listView.setAdapter(...);
return view;
}
I have then read about the method onActivityCreated
and read that I need to setup the view inside that and not onCreateView
so I wrote my self some code to do the same
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, container, false);
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
if(view == null){
throw new NullPointerException("View returned null inside onActivityCreated this shouldn't have happened!");
}
ListView listView = view.findViewById(...);
listView.setAdapter(...);
}
I'm really curious what's the difference here? And which should be used? Which one does android recommend you to use?