Reverse Gear
Reverse Gear

Reputation: 27

Method call on changing tabs in viewpager

How to call a method in a fragment when the tab is changed. I tried using onPause() in fragment, but it is not getting invoked. I am using ViewPager.

Thanks!

Upvotes: 1

Views: 1630

Answers (3)

Abhishek shrivastava
Abhishek shrivastava

Reputation: 19

You can use interfaces here. Define your interface in Activity that contains view pager

public interface MyInterface{
     void callMethod();
}

initialize interface and call like this

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
     public void onPageScrollStateChanged(int state) {

     }
     public void onPageScrolled(int position, float positionOffset, 
     int positionOffsetPixels) {

     }

     public void onPageSelected(int position) {
       myInterface.callMethod();
    }
    });

And implement that method in your fragment and call your method in callback.

Myfragment extends Fragment implements MyInterface{
 //
  @Override
  void callMethod(){
     //call your method here
  }

}

Upvotes: 0

Kruti Parekh
Kruti Parekh

Reputation: 1291

You can override setUserVisibleHint(boolean isVisibleToUser) method and use it for this purpose. isVisibleToUser will be true when the tab is changed and the fragment is selected and in other fragment which was previously visible, this method will be called with false.

EDIT: setUserVisibleHint will be called multiple times. But in that case, you can rely on getActivity() not being null. i.e. if (isVisibleToUser && getActivity() != null)

Upvotes: 1

Jay Patel
Jay Patel

Reputation: 516

Add ViewPager.OnPageChangeListener to ViewPager by:

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
       <method call>
    }
}

So whenever user swipes through pages of ViewPager, you will get callback in onPageSelected() method with position of that page and there you can call fragment's method

Upvotes: 0

Related Questions