android中心对齐tablayout中的选定选项卡 [英] android center align the selected tab in tablayout

查看:28
本文介绍了android中心对齐tablayout中的选定选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 android support design tablayout.这是我的代码:

I am using android support design tablayout. Here's my code:

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

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

我的问题是标签总是左对齐.但是,我想将选定的选项卡居中(即使在开始时,第一个(选定的)选项卡也应该居中).有没有办法做到这一点?谢谢.

My issue is the tabs always align left. However, I would like to center the selected tab (even at the beginning, the first(selected) tab should be centered). Is there a way to do this? Thanks.

推荐答案

我看了一下 TabLayout 和 tabContentStart 只为它的第一个孩子设置了 padding -> SlidingTabStrip,所以我在两边都手动设置了:

I took a look into TabLayout and tabContentStart only sets padding for its first child -> SlidingTabStrip, so I set it manually on both sides:

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

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

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

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        View firstTab = ((ViewGroup)getChildAt(0)).getChildAt(0);
        View lastTab = ((ViewGroup)getChildAt(0)).getChildAt(((ViewGroup)getChildAt(0)).getChildCount()-1);
        ViewCompat.setPaddingRelative(getChildAt(0), (getWidth()/2) - (firstTab.getWidth()/2),0,(getWidth()/2) - (lastTab.getWidth()/2),0);
    }
}

TabLayout 的第一个 0 索引子项是 SlidingTabStrip.

TabLayout's first 0 index child is the SlidingTabStrip.

这篇关于android中心对齐tablayout中的选定选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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