I would like to make a slide programmatically in my ViewPager.
My problem is, that the event to slide is called by a button that is placed inside of a fragment that is hold by the ViewPager.
I know about the code:
viewpager.setCurrentItem(int index)
And now I my thought was to make the ViewPager variable public static to access it from the child fragment. But the static variable is not accessible from the child fragment.
How can I achieve this to make a slide by clicking on a button that is placed inside of a page?
You can use an interface to interact with your ViewPager via your Activity (or a Fragment hosted in said Activity) without exposing any fields.
Inside the ViewPager Fragment, create an interface:
public class FragmentInViewPager extends Fragment {
    private Callback mCallback;
    public interface Callback {
        void setViewPagerCurrentPage(int page);
    }
    @Override
    public void onAttach(Activity activity) {
        mCallback = (Callback) activity; 
        //NB: The above will throw ClassCastException if your Activity
        //Does not implement FragmentInViewPager.Callback
    }
    //To call it...
    int newPageNumber = 27;
    mCallback.setViewPagerCurrentPage(newPageNumber);
Have your Activity implement the interface, and from there interact with your ViewPager directly (if it is a variable in your Activity) or access it in one of your fragments:
public class MainActivity extends AppCompatActivity implements FragmentInViewPager.Callback {
    private ViewPager mViewPager;
    //...
    @Override
    public void setViewPagerCurrentPage(int page) {
        mViewPager.setCurrentItem(page);
        //Or...if it is inside another Fragment...
        ViewPagerFragment frag = (ViewPagerFragment) getFragmentManager().findFragmentByTag("view_pager_fragment_tag");
        if (frag != null) frag.getViewPager().setCurrentItem(page);
    }
                        Inside your childFragment you have to get a reference to the Fragement which holds your Viewpager.
FragmentViewPager fragmentViewPager = (FragmentViewPager) getActivity().getSupportFragmentManager().findFragmentByTag(yourTag);
Setting viewpager to public is sufficient. Then you can call
fragmentViewPager.viewpager.setCurrentItem(index);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With