TabLayout not filling width when tabMode set to 'scrollable'

前端 未结 17 793
傲寒
傲寒 2020-12-02 16:58

I have added TabLayout (from support library v22.2.1) to my Fragment as:



        
17条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 17:22

    I have tried almost all answeres, atlast found this one works like a charm.

    public void dynamicSetTabLayoutMode(TabLayout tabLayout) {
                int tabWidth = calculateTabWidth(tabLayout);
                int screenWidth =  getApplicationContext().getResources().getDisplayMetrics().widthPixels;
                if (tabWidth <= screenWidth) {
                    tabLayout.setTabMode(TabLayout.MODE_FIXED);
                } else {
                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                }
            }
        
          private int calculateTabWidth(TabLayout tabLayout) {
                int tabWidth = 0;
                for (int i = 0; i < tabLayout.getChildCount(); i++) {
                    final View view = tabLayout.getChildAt(i);
                    view.measure(0, 0); 
                    tabWidth += view.getMeasuredWidth();
                }
                return tabWidth;
            }
    

提交回复
热议问题