-2

How to change Tab layout tab background in Android programmatically

Please see the below codes. I want to change the drawable colors through programmatically.

This is my xml code.

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout_pay_options"
    android:layout_width="match_parent"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginLeft="5dp"
    android:layout_height="0dp"
    android:layout_weight="1"
    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"
    app:tabBackground="@drawable/custom_tab_button"
    app:tabTextColor="@color/tool_bar_background"
    app:tabSelectedTextColor="@color/white" />

This is my drawable.

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

<stroke android:width="1dp"
android:color="@android:color/transparent"/>

<corners android:bottomLeftRadius="50dp"
android:bottomRightRadius="50dp"
android:topLeftRadius="50dp"
android:topRightRadius="50dp"/>

</shape>
</item>
<item android:state_selected="false">
<shape android:shape="rectangle">
<solid android:color="#e1e1e1"/>

<stroke android:width="1dp"
android:color="@android:color/transparent"/>

<corners android:bottomLeftRadius="50dp"
android:bottomRightRadius="50dp"
android:topLeftRadius="50dp"
android:topRightRadius="50dp"/>

</shape>
</item>
</selector>
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

Normally you can do it as below.

 tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
Remees M Syde
  • 2,564
  • 1
  • 19
  • 42
1

Set tab text color this way :

tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator)
Remees M Syde
  • 2,564
  • 1
  • 19
  • 42
Rashpal Singh
  • 633
  • 3
  • 13