Search code examples
javaandroidandroid-tabactivity

How to switch tabs from a fragment using a button?


I have a tabbed Activity with several tab Fragments. (like artists, playlists, albums). I want to add a buttons to my home Fragment that will navigate to the other tabs after being click. For example: i click on playlists and it takes me 3 tabs over to playlists. I have no Idea how to go about this.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_home, container, false);
    playlists = (Button) rootView.findViewById(R.id.playlists);
    playlists.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //getActivity().getTabHost().setCurrentTabByTag("TAB2");
            //viewPager.setCurrentItem(2);


        }
    });


    return rootView;
}

enter image description here


Solution

  • Declare an interface in HomeFragment and declare listener variable

    private HomeFragmentActionListener mListener;
    
        public interface HomeFragmentActionListener { 
                void onButtonClick(int pos);
            }
    

    set this listener variable in HomeFragment class.

    public void setListener(
                HomeFragmentActionListener listener) {
            mListener = listener;
        }
    

    and onButton click inform the listener

    playlists.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //getActivity().getTabHost().setCurrentTabByTag("TAB2");
                //viewPager.setCurrentItem(2);
              mListener.onButtonClick(2);
            }
        });
    

    Implement this interface under MainFragment

    public class MainFragment extends Fragment {
    
     private class HomeFragmentListener implements HomeFragment.HomeFragmentActionListener {
    public void onButtonClick(int pos) {
     //Change the tabs.
    }
    }
    and set the listener in setupviewpager
    private void setupViewPager(ViewPager viewPager) { 
    Adapter adapter = new Adapter(getChildFragmentManager()); 
    HomeFragment homeFragment = new HomeFragment(); 
    homeFragment.setListener( new HomeFragmentListener()); 
    adapter.addFragment(homeFragment, this.getString(R.string.Homecap)); 
    ..