OnClickListener on Tabs not working

此生再无相见时 提交于 2019-11-27 19:55:14

If you want to see that a particular tab is clicked, you need to add your listener to the tab itself, not the TabHost.

The hierarchy of views in a tab implementation is:

  • TabHost
    • TabWidget
      • (tab)
      • (tab)
    • FrameLayout

The tabs are added at runtime by calling: tabHost.addTab(tabHost.newTabSpec(""));

You can then get a handle to the individual tabs by calling: getTabWidget().getChildAt(4);

In essence, you are adding your OnClickListener to a child of the TabWidget. You can now pick up the clicks on your individual tab. However, this will override the default behavior which changes the content when a tab is clicked. So, to get your content to change, your OnClickListener will need to do that for you.

Here is a full example, which lets you intercept the click event, and change the content below the tab:

final String myTabTag = "My Tab";
final int myTabIndex = 3;

getTabHost().addTab( getTabHost().newTabSpec(myTabTag) );

getTabWidget().getChildAt(myTabIndex).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (getTabHost().getCurrentTabTag().equals(myTabTag)) {
            getTabHost().setCurrentTab(myTabIndex );
        }
    }
});

use setOnTabChangedListener instead of OnClickListener ;)

    static TabHost tabHost;

    tabHost = getTabHost();


    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
       @Override
      public void onTabChanged(String arg0) {
       Log.i("******Clickin Tab number ... ", "" + tabHost.getCurrentTab());
      }     
});  
martin

Your clause is wrong, use:

...

if (getTabHost().getCurrentTabTag().equals(myTabTag) == false) {
            getTabHost().setCurrentTab(myTabIndex );
   }

...

into my code, it shows some errors and ask me to create new methods in those names like getTabWidget(), getTabHost(), etc. Waiting for your response.

Try this

 tabHost.getTabHost().setCurrentTab(myTabIndex);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!