Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-fragmentactivityviewpagerindicator

Refresh fragment inside viewpager


In my example am having a view pager inside a fragment and tabs in View pager are crated dynamically. For example, am having tab for three subjects Sub 1, Sub 2, Sub 3 each subject tab having some number of questions. Now what i want is when i switch from one tab to another tab should be reloaded or refreshed.

I have google a lot what i found to refresh the fragment is

Fragment currentFragment = getFragmentManager().findFragmentByTag("FRAGMENT");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();

So is this is only way to refresh Tab fragment or any suggestions?


Solution

  • From your question it is clear you are able to get to work fine when loaded first time. So ones loaded, for refreshing the fragment when user swipe the tab you can override setUserVisibleHint method inside Fragment class which is loaded in viewpager.

    You can do something like this:

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser){
            //This means this fragment is visible to user so you can write code to refresh the fragment here by reloaded the data. 
        }
    }
    

    Note: setUserVisibleHint is called before onCreateView so this will not work when loading the fragment first time.