当tabMode设置为"scrollable"时,TabLayout无法填充宽度 [英] TabLayout not filling width when tabMode set to 'scrollable'

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

问题描述

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

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"/>

问题在于,当片段的方向为横向时(在片段的初始创建之前或之后),TabLayoutFragment的宽度不匹配(是的,父对象的宽度设置为match_parent).

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):

如果将tabMode更改为固定,将填充宽度,但制表符太小.有什么合适的解决方案吗?

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设置为"scrollable"时,TabLayout无法填充宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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