0

enter image description hereI'm using Tablayout and i want to change background of selected tab indicator and also set his width. how can I achive this in my project

I want to make tab selector like on the above image

Bhushan
  • 117
  • 7

1 Answers1

1

To setting the width, use below code:

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

}

for changing the bakground:

res/layout/somefile.xml:

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

and then in 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>
prat
  • 795
  • 5
  • 14