android-viewpager – android中心在tablayout中对齐选定的选项卡

我正在使用 android支持设计tablayout.这是我的代码:
<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"
        />

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

解决方法

我看了一下TabLayout,tabContentStart只为其第一个孩子设置了填充 – > SlidingTabStrip,所以我在两边手动设置:
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),(getWidth()/2) - (lastTab.getWidth()/2),0);
    }
}

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

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...