我真的很好奇在Fragment中设置视图的最佳实践。自从我开始为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;
}
然后,我了解了方法onActivityCreated
,并了解到我需要在其中而不是onCreateView
内设置视图,因此我为自己编写了一些代码来做同样的事情
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(...);
}
我真的很好奇这里有什么区别?而应该使用哪个呢? android建议您使用哪一个?