Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Code Each Time a Fragment in FramentStatePagerAdapter is viewed

I am using a FragmentStatePagerAdapter to create a SlidingTabLayout with 3 tabs. I want to do something each time a Fragment is viewed on my screen. I've tried putting what I want to happen inside the onStart() of the respective fragment like so:

public void onStart() {
    //Do This
}

but it only works when the Fragment is moved 2 fragments away (i.e. 1st to 3rd, 3rd to 1st). Is there a way to do something each time a fragment is viewed on screen?

like image 718
Solomon Powell Avatar asked Nov 21 '25 14:11

Solomon Powell


1 Answers

you can override setUserVisibleHint()

public class MyFragment extends Fragment {
  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) { 
       // here fragment is visible to user
    }
    else {  
    }

  }
}
like image 166
N J Avatar answered Nov 23 '25 04:11

N J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!