当 tabMode 设置为“可滚动"时,TabLayout 不填充宽度 [英] TabLayout not filling width when tabMode set to 'scrollable'

查看:44
本文介绍了当 tabMode 设置为“可滚动"时,TabLayout 不填充宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 TabLayout(来自支持库 v22.2.1)添加到我的 Fragment 中:

当屏幕宽度足够大以显示所有选项卡时(请参阅右侧的空白区域):

如果我将 tabMode 更改为固定,宽度会被填充但标签太小.有没有合适的解决方案?

解决方案

我想这是实现您想要的最简单的方法.

public class CustomTabLayout extends TabLayout {公共 CustomTabLayout(上下文上下文){超级(上下文);}公共 CustomTabLayout(上下文上下文,AttributeSet attrs){超级(上下文,属性);}公共 CustomTabLayout(上下文上下文,AttributeSet attrs,int defStyleAttr){超级(上下文,属性,defStyleAttr);}@覆盖protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);尝试 {如果 (getTabCount() == 0)返回;Field field = TabLayout.class.getDeclaredField("mTabMinWidth");field.setAccessible(true);field.set(this, (int) (getMeasuredWidth()/(float) getTabCount()));} 捕获(异常 e){e.printStackTrace();}}}

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

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/MyColorAccentTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>

The issue is that when the Fragment's orientation is landscape (before or after the initial creation of the fragment), the TabLayout doesn't match the width of the Fragment (yes the parent has its width set to match_parent as well).

When screen width is small (i.e not all tabs can be shown at same time):

When screen width is big enough to show all tabs (see the blank space at the right):

If I change tabMode to fixed, width is filled but tabs are too small. Is there any proper solution out there?

解决方案

I guess this is the simpliest way to achieve what you want.

public class CustomTabLayout extends TabLayout {
    public CustomTabLayout(Context context) {
        super(context);
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        try {
            if (getTabCount() == 0)
                return;
            Field field = TabLayout.class.getDeclaredField("mTabMinWidth");
            field.setAccessible(true);
            field.set(this, (int) (getMeasuredWidth() / (float) getTabCount()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这篇关于当 tabMode 设置为“可滚动"时,TabLayout 不填充宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆