Search code examples
androidandroid-tablayout

TabLayout clicked or switched


I have TabLayout with 2 tabs. I have this code:

mTabLayoutLogin.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
           //do something
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
           //do something else
        }

Is there a way to know, when switching to a tab, that the user clicked the tab or the code switched intentionally to tab (like this code mTabLayoutLogin.getTabAt(1).select())?

Thanks


Solution

    1. (Hacky solution) You can try combination of overriding Activity.dispatchTouchEvent(MotionEvent event) and your addOnTapSelectedListener method, if both trigger simultaneously it is probably due to user click not by code trigger.

    From the docs http://developer.android.com/reference/android/app/Activity.html#dispatchTouchEvent(android.view.MotionEvent)

    1. (Elegant solution) When ever called from code trigger a flag(could be boolean) as well.