0

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?

Meenaxi
  • 567
  • 5
  • 17

1 Answers1

1

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.

Rajen Raiyarela
  • 5,526
  • 4
  • 21
  • 41
  • Ok, let me try this. I want to make call oncreateView() each time so is it possible? – Meenaxi May 06 '15 at 11:47
  • you can create a method which loads the data .... so call that method from oncreateview() as well as from setUserVisibleHint. but make sure when calling from setUserVisibleHint you need to put check if the control is not null then only assign value else skip – Rajen Raiyarela May 06 '15 at 11:51