我应该在onCreateView、onViewCreated还是onActivityCreated中初始化我的回收器视图?
这3个之间有什么区别,我搜索了解释,但有些人说使用onCreateView,有些人说使用onViewCreated或onActivityCreated并且只使用onCreateView来膨胀布局?
这是我的代码
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerViewSongs = rootView.findViewById(R.id.recyclerViewSongs);
initRecyclerView();
Log.e(TAG, "onCreateView called!");
return rootView;
}
private void initRecyclerView() {
Main.musicList = Main.songs.songs;
// Connects the song list to an adapter
// (Creates several Layouts from the song list)
allSongsAdapter = new AllSongsAdapter(getContext(), Main.musicList);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerViewSongs.setLayoutManager(linearLayoutManager);
recyclerViewSongs.setHasFixedSize(true);
recyclerViewSongs.setAdapter(allSongsAdapter);
recyclerViewSongs.addOnItemTouchListener(new OnItemClickListeners(getContext(), new OnItemClickListeners.OnItemClickListener() {
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onItemClick(View view, int position) {
Toast.makeText(getContext(), "You Clicked position: " + position, Toast.LENGTH_SHORT).show();
if (! Main.songs.isInitialized())
return;
//Start playing the selected song.
playAudio(position);
}
}));
}
onCreateView()
将是最好的选择,因为您使用的是Fragment
。不同之处在于onCreateView()
是onCreate()
for Activity的Fragment
等价物,在View
创建期间运行,但onViewCreated()
在View
创建后运行。
和onActivityCreated()
调用onCreate()
方法的Activity
完成后,你可以在这里看到:https://stackoverflow.com/a/44582434/4409113
最好的设置级别是onCreateView(),在Activity的情况下相当于onCreate(),因为RecyclerView需要快速,以免UI缓慢。因此,onViewCreated()中的RecyclerView将在填充UI之前使UI缓慢。