Fragment Recyclerview onCreateView、onViewCreated 还是 onActivityCreated?

Vin*_*nce 6 java android android-fragments android-recyclerview fragment-oncreateview

我应该在 onCreateView、onViewCreated 还是 onActivityCreated 中初始化我的回收视图?

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

}
Run Code Online (Sandbox Code Playgroud)

ʍѳђ*_*ઽ૯ท 2

onCreateView()将是您使用后的最佳选择Fragment。区别在于,onCreateView()相当于FragmentonCreate()活动”,并且在View创建期间运行,但在创建onViewCreated()之后运行。View

并在完成方法onActivityCreated()后调用,如下所示: https: //stackoverflow.com/a/44582434/4409113onCreate()Activity