我应该在 onCreateView、onViewCreated 还是 onActivityCreated 中初始化我的回收视图?这三个之间有什么区别,我搜索了解释,但有些人说使用 onCreateView ,有些人说使用 onViewCreated 或 onActivityCreated 并且只使用 onCreateView 来膨胀布局?这是我的代码@Overridepublic 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); } }));}
2 回答
慕斯王
TA贡献1864条经验 获得超2个赞
onCreateView()将是最佳选择,因为您正在使用Fragment. 所不同的是onCreateView()是Fragment等价的onCreate()各种活动和运行期间View创建,但onViewCreated()运行后View已创建。
并在完成方法onActivityCreated()之后调用
慕工程0101907
TA贡献1887条经验 获得超5个赞
设置 RecyclerView 的最佳级别是在 onCreateView() 中,在 Activity 的情况下相当于 onCreate() 因为 RecyclerView 需要快速以免使 UI 变得迟钝。因此,onViewCreated() 中的 RecyclerView 会使 UI 在填充 UI 之前变得缓慢。
添加回答
举报
0/150
提交
取消
