How to programmatically switch tabs using buttonclick in Android

不问归期 提交于 2019-11-28 10:45:47

Here's a code example that you can put inside your onClick(). It's as Mark and Kevin described.

    TabActivity tabs = (TabActivity) getParent();
    tabs.getTabHost().setCurrentTab(2);

I've used this code tidbit numerous times. Hope this clarifies.

There is no widget with @android:id/tabhost in the current activity. Hence, findViewById() returns null, and your call to setCurrentTab() fails.

Now, my guess is that is because you are putting activities in your tabs. Had you put Views in your tabs, your code would work. Your code would also be faster, take up less heap space, and be at reduced risk of running out of stack space.

If you wish to stick with your current implementation, try calling getParent().findViewById() instead of just findViewById().

Suragch

2017 answer

The other answers here appear to be outdated. The Creating Swipe Views with Tabs documentation recommends using TabLayout with a ViewPager.

Here is one partial implementation of the code to do this.

public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private Button mButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...

        mViewPager = (ViewPager) findViewById(R.id.fieldspager);

        // ...

        mButton.setOnClickListener(myButtonClickHandler);
    }


    View.OnClickListener myButtonClickHandler = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mViewPager.setCurrentItem(2, true);
        }
    };
}

From the code above, setting the tab programmatically is done like this:

mViewPager.setCurrentItem(2, true); // set it to the third tab

Here is another implementation with more details of how the view pager and tab layout are set up.

This works for me

getActionBar().setSelectedNavigationItem(0);

Update: plugging my code into the question's code to give it more context...

ImageButton next = (ImageButton) findViewById(R.id.ButtonAsk);
next.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View view)
    {
        getActionBar().setSelectedNavigationItem(2);
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!