如何适应android中的标签宽度屏幕

如何适应android中的标签宽度屏幕,android,android-support-library,android-tablayout,Android,Android Support Library,Android Tablayout,我使用android支持库实现选项卡布局,它看起来像 这里的标签宽度与屏幕不匹配,我的布局不正确 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="m

我使用android支持库实现选项卡布局,它看起来像

这里的标签宽度与屏幕不匹配,我的布局不正确

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>


试着将主容器中孩子的重力设置为中心。理想情况下,应该将内容移动到屏幕中央

尝试在
表格布局中调用这些方法

tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

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

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();
        }
    }
}
“更简单”的答案是在您的TabLayout xml中添加app:tabMaxWidth=“0dp”:

<android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMaxWidth="0dp"
            app:tabGravity="fill"
            app:tabMode="fixed" />


事实上,我想让标签与设备屏幕配合尝试在您的表格布局中使用重力,我认为它们会自动工作,否则必须使用较大字体的样式为它们创建自定义视图,这可能会有所帮助,但不确定