Toggle Tabs in ViewPager via button by fragment

0

I wonder if there is any way to switch between tabs by the fragment itself. I have a ViewPager with 2 tabs and I would like to switch via buttons because I validate some fields before switching the tabs.

I disabled the swipe and also the action bar to avoid switching tabs without validating the output data. I did not post any code because I need to know just how to call another tab via button. the rest of the code is unnecessary I believe

 public void changePagerItem(int pageNumber) {
    mViewPager.setCurrentItem(1);
}

method implemented in class main

btnFinalizar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ValidaPedidoAcp();
            ValidaPedidoObs();
            ValidaPedidoOpc();
            FastFoodPedidoActivity tabs = (FastFoodPedidoActivity)getActivity().getParent();
            tabs.changePagerItem(0);
        }
    });

method implemented in button ... but gives the following error

Process: com.meuapp.example, PID: 4048
     java.lang.NullPointerException: Attempt to invoke virtual method 'void Pedidos.FastFoodPedidoActivity.changePagerItem(int)' on a null object reference
         at Pedidos.Tabs.TabAdicionais$2.onClick(TabAdicionais.java:282)
         at android.view.View.performClick(View.java:6219)
         at android.view.View$PerformClick.run(View.java:24482)
         at android.os.Handler.handleCallback(Handler.java:769)
         at android.os.Handler.dispatchMessage(Handler.java:98)
         at android.os.Looper.loop(Looper.java:164)
         at android.app.ActivityThread.main(ActivityThread.java:6540)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
    
asked by anonymous 04.08.2017 / 21:30

1 answer

0

You will only need to set a method in your activity to change the ViewPager item and then make a reference to < strong activity from which the fragment is bound and you will have free access to the method

// ExampleActivity() ...
public void changePagerItem(Int pageNumber) {
    yourViewPager.setCurrentItem(page);
}

// Fragment() ...
((ExampleActivity) getActivity()).changePagerItem(3);
    
04.08.2017 / 21:41