Skip to content Skip to sidebar Skip to footer

Restart Fragment Class When Back Button Press

I have a fragment that is part of tab view. I want to restart this fragment when I press back button. but i don't know how to refresh it. i tried some codes like this: Restart frag

Solution 1:

Use this code:

YourFragmentClassfragment= (YourFragmentClass) 
getFragmentManager().findFragmentById(R.id.your_fragment_container_id)

getFragmentManager().beginTransaction()
                    .detach(fragment)
                    .attach(fragment)
                    .commit();

& this will cause your fragment's OnCreateView method to be called again & refresh its layout.

UPDATE:

When using the Support Library, you could access your fragment this way:

int YOUR_FRAGMENT_POSITION = 2; // in your case you wanna access the 3rd fragment, 0 indexed

YourFragmentClass fragment = (YourFragmentClass) getSupportFragmentManager().getFragments().get(YOUR_FRAGMENT_POSITION);

And use the same code snippet above:

getSupportFragmentManager().beginTransaction()
                        .detach(fragment)
                        .attach(fragment)
                        .commit();

If you try to access your fragment via the PagerAdapter, you may end up with an IllegalStateException, telling you that the fragment has failed to save its state.

Post a Comment for "Restart Fragment Class When Back Button Press"