片段Recyclerview onCreateView,onViewCreated或onActivityCreated?

时间:2018-09-26 16:50:01

标签: java android android-fragments android-recyclerview fragment-oncreateview

我应该在onCreateView,onViewCreated或onActivityCreated中初始化我的recyclerview吗?

这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);
            }
        }));

}

2 个答案:

答案 0 :(得分:0)

onCreateView()将是最佳选择,因为您正在使用Fragment。区别在于onCreateView()Fragment的{​​{1}}等效,并且在onCreate()创建期间运行,而ViewonViewCreated()创建之后运行已创建。

View的{​​{1}}方法完成后,onActivityCreated()调用如下所示:https://stackoverflow.com/a/44582434/4409113

答案 1 :(得分:0)

设置RecyclerView的最佳级别是onCreateView(),它与Activity时的onCreate()等效,因为RecyclerView需要快速以免UI变慢。因此,在填充UI之前,onViewCreated()中的RecyclerView将使UI变慢。