Android TabWidget detect click on current tab

前端 未结 9 2132
庸人自扰
庸人自扰 2020-11-28 05:34

I am trying to find way to be able to fire an onclick event on a tab when this tab is the current tab.

I did try this way (among several other) with no success thou

9条回答
  •  孤独总比滥情好
    2020-11-28 06:16

    The problem here is that setOnTabChangedListener does not fire when clicking on the selected tab, and if you set an OnClickListener on the tab, you lose the normal tab behavior.

    So an easy solution is to put OnClickListener on the tab, and inside it, set programatically that this is the current tab.

    With TabHost:

    getTabWidget().getChildAt(0).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom code
            tabHost.setCurrentTab(0);                                    
        }
    });
    

    With TabLayout

    tabLayout.getTabAt(0)setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        // custom code
                        TabLayout.Tab tab  = tabLayout.getTabAt(0);
                        tab.select();
                    }
                }
            });
    

提交回复
热议问题