How can I recreate a fragment?
If you're using Navigation Component, you can use this:
findNavController().navigate(
R.id.current_dest,
arguments,
NavOptions.Builder()
.setPopUpTo(R.id.current_dest, true)
.build()
)
This lets NavController pop up the current fragment and then navigate to itself. You get a new Fragment and fragment ViewModel also gets recreated.
You can use :
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, LobbyFragment.newInstance()).commit();
To recreate your fragment
Note:getSupportFragmentManager()
is if you are using support fragment and AppCompatActivity , if you are using framework fragment class you need to use getFragmentManager()
I'm using .detach()
and .attach()
for recreating the fragment.
ATTACH
Re-attach a fragment after it had previously been deatched from the UI with detach(Fragment). This causes its view hierarchy to be re-created, attached to the UI, and displayed.
DETACH
Detach the given fragment from the UI. This is the same state as when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.
HOW I USE IT
getFragmentManager()
.beginTransaction()
.detach(LobbyFragment.this)
.attach(LobbyFragment.this)
.commit();