如何在 android 中使用 TabHost.OnTabChangeListener?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2243360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:08:16  来源:igfitidea点击:

How to use TabHost.OnTabChangeListener in android?

android

提问by Praveen

How to use TabHost.OnTabChangeListener in android?

如何在 android 中使用 TabHost.OnTabChangeListener?

give me some example code... :(

给我一些示例代码... :(

thanks

谢谢

回答by pgsandstrom

why it would be my pleasure to help you good sir:

为什么我很乐意帮助您,好先生:

myTabHost.setOnTabChangedListener(new OnTabChangeListener(){
@Override
public void onTabChanged(String tabId) {
    if(TAB_1_TAG.equals(tabId)) {
        //destroy earth
    }
    if(TAB_2_TAG.equals(tabId)) {
        //destroy mars
    }
}});

Where TAB_1_TAGis the tag provided to the newTabSpecmethod when creating the tab.

创建选项卡时TAB_1_TAG提供给newTabSpec方法的标签在哪里。

回答by jake_hetfield

I think in many cases it makes sense to make your TabActivity the listener:

我认为在许多情况下,让您的 TabActivity 成为侦听器是有意义的:

public class MyTabActivity extends TabActivity implements OnTabChangeListener {

    private TabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* Your onCreate code here */

        tabHost.setOnTabChangedListener(this);
    }

    /* ... */

    @Override
    public void onTabChanged(String tabId) {
        /* Your code to handle tab changes */
    }
}

回答by stevyhacker

You can use OnTabSelectedListener, here is an example.

您可以使用OnTabSelectedListener,这是一个示例。

  tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
    });