1

I'm using viewPager to create a layout with tabs and in each tab I use a Fragment. One of them is to get all de user contacts and put it on a ListView. But I want to call de AssyncTask only if the Fragment is displayed on screen.

is there a method to do it? TY

Eduardo Bonfa
  • 290
  • 1
  • 4
  • 15

3 Answers3

2

Start your AsyncTask in onStart which is the method called once the fragment becomes visible to the user. onCreateView will be called even if the fragment doesn't become visible. See also: http://developer.android.com/reference/android/app/Fragment.html#onStart()

I would however recommend to use a loader instead of AsyncTask (e.g. an AsyncTaskLoader http://developer.android.com/reference/android/content/AsyncTaskLoader.html).

Emanuel Moecklin
  • 28,488
  • 11
  • 69
  • 85
1

you can use

@Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser)
    {
       //things to do when fragment is visible
    }
}

Even it is called before onCreateView.

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
Dharmaraj
  • 1,256
  • 13
  • 12
0

You can check to see if it's visible with .isVisible() something like this

MyFragmentClass fragment = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("fragmentTAG");

if (fragment != null && fragment.isVisible()) {
     // call AsyncTask
}
Claud
  • 1,065
  • 3
  • 26
  • 38