Skip to content Skip to sidebar Skip to footer

How To Set A Tab Listener To An Actionbar

i'm trying to do a Tab Layout on android, and i'm trying to add tab ton the action bar but its not working. My probleme is that in this step of the function setTabListener((android

Solution 1:

.setTabListener((android.app.ActionBar.TabListener) actionBar)

is wrong because actionBar dose not implement listener, you must implement thelistener in your fragment or in your activity and then call for example in your fragment:

setTabListener(this);

for example this is sample code for activity:

publicclassMainActivityextendsFragmentActivityimplementsActionBar.TabListener {

    ViewPager viewPager=null;
    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ActionBar actionBar=getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        addTabs(actionBar);


        }
    privatevoidaddTabs(ActionBar actionBar)
    {
        ActionBar.Tab tab1=actionBar.newTab();
        tab1.setText("Tab 1");
        tab1.setTabListener(this);

        ActionBar.Tab tab2=actionBar.newTab();
        tab2.setText("Tab 2");
        tab2.setTabListener(this);

        ActionBar.Tab tab3=actionBar.newTab();
        tab3.setText("Tab 3");
        tab3.setTabListener(this);

        actionBar.addTab(tab1);
        actionBar.addTab(tab2);
        actionBar.addTab(tab3);
    }

    @OverridepublicvoidonTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @OverridepublicvoidonTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @OverridepublicvoidonTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }
}

}

Update:

for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(YourFragment.this); }

Post a Comment for "How To Set A Tab Listener To An Actionbar"