Search code examples
androidkotlinandroid-tablayout

Set textcolor only one tab on tablayout


I want to set textColoronly one tab on tablayout. One tab must have another color by default. Here is my Tablayout in XML

 <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabTextColor="@color/colorWhite"
        app:tabIndicatorColor="@color/colorPrimary"
        android:background="@color/colorBackground"
        app:tabMode="fixed" />

It make all tabs color white. I have tried this:

tabs_main.getTabAt(3)?.icon?.alpha = 225

but It doesn't work How can I change one tab color?


Solution

  • With alpha you are changing the opacity of the inside text, not the color.

    If this is what you want to achieve, then check if tabs_main.getTabAt(3) doesn't return null.

    Otherwise, I suggest you to use a custom TextView inside the tab element.

    Example:

    Create a layout : custom_text_view.xml

      <?xml version="1.0" encoding="utf-8"?>
      <TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/customTabTextView"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:textColor="@color/your_color"
          android:textSize="14sp" />
    

    Add the layout as custom view for each tab item, and choose the desired textColor for each of them.

        (0..tabLayout.tabCount).forEach { position ->
            val customTextView = LayoutInflater.from(this).inflate(R.layout.custom_text_view, null)
            // Set the text color
            customTextView.setTextColor(ContextCompat.getColor(applicationContext, R.color.<name_of_color>))
            tabLayout.getTabAt(position)?.customView = customTextView
        }