简体   繁体   中英

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.

Try calling actionBar.setSelectedNavigationItem(x):

int position = 1;
getSupportActionBar().setSelectedNavigationItem(position);

In my app I have one tab fragment that has an album of pictures. When the user clicks on one of the pictures it causes that picture to be displayed in a ViewPager on the other tab fragment and automatically switches to that tab with setCurrentTabByTag().

public class EditAlbumTabs extends SherlockFragmentActivity {
   TabHost mTabHost;
   TabsAdapter mTabsAdapter;

   public void onPagerPositionSet(int pagerPosition, String[] imageUrls) {
        FragmentFlash fragmentFlash = (FragmentFlash)mTabsAdapter.getFragment("flash");
        if (fragmentFlash != null) {
           fragmentFlash.pagerPositionSet(pagerPosition, imageUrls);
           **mTabHost.setCurrentTabByTag("flash");**
        }
   }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_tabs_pager);
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    mViewPager = (ViewPager)findViewById(R.id.pager);
    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
    mTabsAdapter.addTab(mTabHost.newTabSpec("album").setIndicator("Album"),
            FragmentAlbumFlashum.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("flash").setIndicator("Flash"),
            FragmentFlash.class, null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM