6

我应该在 onCreateView、onViewCreated 还是 onActivityCreated 中初始化我的 recyclerview?

这三个有什么区别,我搜索了解释,但有人说使用 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);
            }
        }));

}
4

2 回答 2

2

onCreateView()将是您使用Fragment. 不同onCreateView()之处在于活动Fragment等效于在创建期间运行,但在创建后运行。onCreate()ViewonViewCreated()View

并在完成方法onActivityCreated()后调用,如您在此处看到的:https ://stackoverflow.com/a/44582434/4409113onCreate()Activity

于 2018-09-26T16:58:15.583 回答
1

设置 RecyclerView 的最佳级别是在 onCreateView() 中,这相当于在 Activity 的情况下的 onCreate(),因为 RecyclerView 需要快速,以免 UI 迟钝。因此,onViewCreated() 中的 RecyclerView 会使 UI 在填充 UI 之前变得迟缓。

于 2018-09-26T17:40:18.730 回答