Recyclerview片段在onCreateView、onViewCreated还是onActivityCreated中创建?

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

}

阅读这个,它会解释一切 https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments - iamkdblue
2个回答

2

onCreateView() 是使用 Fragment 时最好的选择。它与 ActivityonCreate() 方法类似,运行在 View 创建期间,但 onViewCreated() 则是在 View 创建后运行。

onActivityCreated() 方法会在 ActivityonCreate() 方法完成后调用,详情请参见:https://dev59.com/k14b5IYBdhLWcg3wlilP#44582434


1

将RecyclerView设置在onCreateView()中是最好的选择,这相当于Activity中的onCreate(),因为RecyclerView需要快速响应,以避免使UI变得缓慢。因此,在填充UI之前,将RecyclerView放在onViewCreated()中会使UI变得缓慢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接