OnClickListener on Tabs not working

后端 未结 4 1253
孤独总比滥情好
孤独总比滥情好 2020-12-05 09:19

Greetings,

I am trying to get the Click - event when clicking on the currently selected tab of my TabActivity. The onTabChangedHandler is only called whenever the ta

相关标签:
4条回答
  • 2020-12-05 09:23

    Your clause is wrong, use:

    ...

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

    ...

    0 讨论(0)
  • 2020-12-05 09:24

    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 );
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-05 09:32

    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);
    
    0 讨论(0)
  • 2020-12-05 09:50

    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());
          }     
    });  
    
    0 讨论(0)
提交回复
热议问题