Selected text color of custom tab in TabLayout

I am trying to create my own tab layout because I need to set an icon counter next to TextView

. I set the id to @android:id/text1

as mentioned in the doc.

When my custom tab is selected, the color of the TextView doesn't automatically change. How to achieve this in the correct and clean way?

Correctly selected default tab:

enter image description here

Invalid custom tab selected (text is gray but should be white):

enter image description here

code

PagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
TabLayout.Tab tab = tabLayout.getTabAt(2);
if (tab != null) { 
    tab.setCustomView(R.layout.tab_proposed_rewards);
}

      

Markup

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@android:id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.Design.Tab"/>

    <TextView
        android:id="@+id/indicator"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:background="@drawable/background_indicator"
        android:gravity="center"
        android:lines="1"/>

</LinearLayout>

      

Edit

Answer:

tab.setCustomView(R.layout.tab_proposed_rewards);
ColorStateList textColor = tabLayout.getTabTextColors();
TextView textView = (TextView) tab.getCustomView().findViewById(android.R.id.text1);
textView.setTextColor(textColor);

      

+3


source to share


1 answer


You can do this programmatically.

Change the selected tab color in the code programmatically. You can use setTabTextColors (int normalColor, int selectedColor)

.

And then apply

yourTabLayout.setTabTextColors (Color.White, Color.Black);

      



Hope this solves your problem, more information can be found at the link

In your case

TabHost tabHost = getTabHost();
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) 
        { 
            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); //Unselected Tabs
            tv.setTextColor(Color.parseColor("#ffffff"));
        } 
        TextView tv = (TextView) tabhost.getCurrentTabView().findViewById(android.R.id.title); //for Selected Tab
        tv.setTextColor(Color.parseColor("#000000"))

      

Try this, it will change the color of the inner text view

+1


source







All Articles