Moving From one tab view to another by button Click Android ActionBar

Renjith Krishnan picture Renjith Krishnan · Dec 12, 2013 · Viewed 8.3k times · Source

I am using http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/ to make Tab bar.

I have also 3 tab first and the second Tab view contains a List view and third on e is Settings.
Settings Contain Reload button. When I clicked the Reload Button I want to move to First Tab.

How can I do this ?

Answer

vipul mittal picture vipul mittal · Dec 12, 2013

Make following changes:

  1. Pass the viewPager reference to your adapter and from adapter to your fragment:

     public class TabsPagerAdapter extends FragmentPagerAdapter {
        ViewPager viewPager;
        public TabsPagerAdapter(FragmentManager fm,ViewPager viewPager) {
            super(fm);
            this.viewPager=viewPager;  
        }
    
        @Override
        public Fragment getItem(int index) {
    
            switch (index) {
            case 0:
                // Top Rated fragment activity
                return new TopRatedFragment(viewPager);
            case 1:
                // Games fragment activity
                return new GamesFragment(viewPager);
            case 2:
                // Movies fragment activity
                return new MoviesFragment(viewPager);
            }
    
            return null;
        }
    
        @Override
        public int getCount() {
            // get item count - equal to number of tabs
            return 3;
        }
    
    }
    
  2. In fragment on click of button call set selection on view pager object:

     public class MoviesFragment extends Fragment {
            private ViewPager viewPager;
            public  MoviesFragment (ViewPager viewPager;){
              this.viewPager=viewPager;
            }
            @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
            rootView.findViewById(<your button>).setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
                    viewPager.setCurrentItem(0);
    
                }
            }); 
            return rootView;
        }
    
    }