Search code examples
androidandroid-fragmentsandroid-actionbarandroid-tabs

Adding Action Bar and Navigation Drawer together without actionbar sherlock


I have already implemented navigation drawer in my app and I want to add swipe Tabs also in my activity. Is it possible to add both these functions in a single activity ? How ? I have searched many ways to make tabs but no success.

I have also tried this link but I don't know how to complete it.


Solution

  • Add this in your onCreate method :

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    

    And to add tabs :

    actionBar.addTab(actionBar.newTab().setText("Title 1").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("Title 2").setTabListener(this));
    ...
    

    And your activity needs to implement ActionBar.TabListener which has onTabSelected method that is called when the user clicks on another tab. You will then do whatever you like.

    To link to tabs to a ViewPager :

    When the user swype the viewpager, change the tab indicator.

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
            }
        });
    

    and when the user clicks on a tab, select the proper page of the viewpager.

    @Override
    public void onTabSelected(Tab tab, android.support.v4.app.FragmentTransaction ft) {
            mViewPager.setCurrentItem(tab.getPosition());
    }