Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment Recyclerview onCreateView, onViewCreated or onActivityCreated?

Should i initialize my recyclerview in onCreateView, onViewCreated or onActivityCreated?

What's the difference between those 3, i searched for explanations but some people say to use onCreateView and some say to use onViewCreated or onActivityCreated And only to use onCreateView to inflate layout?

This is my code

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

}
like image 512
Vince VD Avatar asked Sep 26 '18 16:09

Vince VD


2 Answers

onCreateView() will be the best choice since you're using Fragment. The difference is onCreateView() is the Fragment equivalent of onCreate() for Activities and runs during the View creation but onViewCreated() runs after the View has been created.

And onActivityCreated() calls after onCreate() method of the Activity completes as you can see in here: https://stackoverflow.com/a/44582434/4409113

like image 67
ʍѳђઽ૯ท Avatar answered Oct 10 '22 18:10

ʍѳђઽ૯ท


The best level to set RecyclerView is in onCreateView() which is equivalent to onCreate() in case of Activity because RecyclerView needs to be quick so as not to make the UI sluggish. Hence, RecyclerView in onViewCreated() will make the UI sluggish before populating UI.

like image 43
Show Young Soyinka Avatar answered Oct 10 '22 20:10

Show Young Soyinka