Search code examples
androidtabsandroid-actionbaractionbarsherlock

On button click go from Activity to ABS specifik tab


i have three tabs in my ABS TabActivity

public class TabActivity extends SherlockFragmentActivity {

    private ViewPager mViewPager;
    private TabAdapter mTabsAdapter;

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

        getOverflowMenu();          

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

        final ActionBar bar = getSupportActionBar();
        bar.setIcon(R.drawable.actionbar_icon);
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mTabsAdapter = new TabAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.tab_icon_join)), 1Fragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.tab_icon_create)), 2Fragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.tab_icon_play)), 3Fragment.class, null);         
    }

In a separate Activity i have a button, on button click i want to go to the second tab. This is what i have so far:

public void onFinishGoToCreate(View view) {
        Intent myIntent = new Intent(Activity.this, TabActivity.class);
        Activity.this.startActivity(myIntent);  
    }

But this takes me to the first tab. Any ideas would be appreciated!


Solution

  • In your activity with the button, you could specify an extra in the intent:

    public void onFinishGoToCreate(View view) {
        Intent myIntent = new Intent(Activity.this, TabActivity.class);
        myIntent.putExtra("selectedTab", 1); // 0 based index for selecting navigation items
        Activity.this.startActivity(myIntent);  
    }
    

    Then, when you've created your tabs in the other activity, you can select the one that's specified in the incoming intent:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        mTabsAdapter.addTab(bar.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.tab_icon_play)), 3Fragment.class, null);         
        int selectedTab = getIntent().getIntExtra("selectedTab", 0); // Default to first tab if nothing has been specified.
        bar.setSelectedNavigationItem(selectedTab);
    }