Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically switch tabs in Android using ActionBarSherlock

I couldn't find any info about this but, how can i programmatically switch tabs in ActionBarSherlock?

Normally when i want to switch views i'd use something like:

Intent intentSecondView = new Intent(this, SecondView.class);
this.startActivity(intentSecondView);

But obviously this doesn't work, because the views in the tabs are fragments.

So is there a way to switch between tabs by code when using ActionBarSherlock??


This is how i add an actionbar with tabs currently.

In my onCreate method i have:

    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.pager);

    setContentView(mViewPager);
    ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mTabsAdapter = new TabsAdapter(this, mViewPager);

    mTabsAdapter.addTab(
            bar.newTab().setText("Fragment 1"),
            MyFragment1.class, null);
    mTabsAdapter.addTab(
            bar.newTab().setText("Fragment 2"),
            MyFragment2.class, null);

I added nothing in my AndroidManifest file to create the tabs. It's all programmatically.

like image 948
w00 Avatar asked Jul 23 '12 09:07

w00


1 Answers

Try calling actionBar.setSelectedNavigationItem(x):

int position = 1;
getSupportActionBar().setSelectedNavigationItem(position);
like image 115
Iñigo Avatar answered Nov 14 '22 20:11

Iñigo