如何更改选定的选项卡指示器背景图像

时间:2016-06-02 05:28:29

标签: android

enter image description here我正在使用Tablayout,我想更改所选标签指示符的背景并设置其宽度。我怎样才能在我的项目中实现这个目标

我想在上面的图片中制作标签选择器

1 个答案:

答案 0 :(得分:1)

要设置宽度,请使用以下代码:

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();
    }
}

}

更改bakground:

<强> RES /布局/ somefile.xml:

<android.support.design.widget.TabLayout
....
app:tabBackground="@drawable/tab_color_selector"
...
/>

然后在选择器res / drawable / tab_color_selector.xml中

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>