TabLayout tab selection

前端 未结 25 1475
情深已故
情深已故 2020-11-29 17:15

How should I select a tab in TabLayout programmatically?

 TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
 tabLayout.setupWithViewPager(viewPager         


        
25条回答
  •  借酒劲吻你
    2020-11-29 17:39

    I am using TabLayout to switch fragments. It works for the most part, except whenever I tried to select a tab programmatically using tab.select(), my TabLayout.OnTabSelectedListener would trigger the onTabSelected(TabLayout.Tab tab), which would cause me much grief. I was looking for a way to do programmatic selection without triggering the listener.

    So I adapted @kenodoggy 's answer to my use. I was further facing a problem where some of the internal objects would return null (because they weren't created yet, because I was answering onActivityResult() from my fragment, which occurs before onCreate() in the case the activity is singleTask or singleInstance) so I wrote up a detailed if/else sequence which would report the error and fall through without the NullPointerException that would otherwise trigger. I use Timber for logging, if you're not using that substitute with Log.e().

    void updateSelectedTabTo(int position) {
        if (tabLayout != null){
            int selected = tabLayout.getSelectedTabPosition();
            if (selected != -1){
                TabLayout.Tab oldTab = tabLayout.getTabAt(0);
                if (oldTab != null){
                    View view = oldTab.getCustomView();
                    if (view != null){
                        view.setSelected(false);
                    }
                    else {
                        Timber.e("oldTab customView is null");
                    }
                }
                else {
                    Timber.e("oldTab is null");
                }
            }
            else {
                Timber.e("selected is -1");
            }
            TabLayout.Tab newTab = tabLayout.getTabAt(position);
            if (newTab != null){
                View view = newTab.getCustomView();
                if (view != null){
                    view.setSelected(false);
                }
                else {
                    Timber.e("newTab customView is null");
                }
            }
            else {
                Timber.e("newTab is null");
            }
        }
        else {
            Timber.e("tablayout is null");
        }
    }
    

    Here, tabLayout is my memory variable bound to the TabLayout object in my XML. And I don't use the scrolling tab feature so I removed that as well.

提交回复
热议问题