Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Pager - slide to next page programmatically with static variable

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?

like image 647
jublikon Avatar asked Nov 08 '15 20:11

jublikon


2 Answers

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);
    }
like image 130
PPartisan Avatar answered Sep 23 '22 16:09

PPartisan


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);
like image 36
Antict Avatar answered Sep 21 '22 16:09

Antict