【问题标题】:Fragment Recyclerview onCreateView, onViewCreated or onActivityCreated?Fragment Recyclerview onCreateView、onViewCreated 还是 onActivityCreated?
【发布时间】:2018-09-26 16:50:01
【问题描述】:

我应该在 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);
            }
        }));

}

【问题讨论】:

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


【解决方案1】:

onCreateView() 将是最佳选择,因为您使用的是Fragment。区别在于 onCreateView() 是 Fragment 等效于活动的 onCreate() 并在 View 创建期间运行,但 onViewCreated() 在 View 创建后运行。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-09-26
      • 1970-01-01
      • 2013-06-16
      • 2014-06-12
      • 2015-05-09
      • 2014-01-06
      • 2011-12-23
      • 1970-01-01
      相关资源
      最近更新 更多