Skip to content Skip to sidebar Skip to footer

Selected Custom Tab Text Color In Tablayout

I'm trying to create custom tab layout because I need to set badge counter next to TextView. I've set id to @android:id/text1 as it's mentioned in doc. When my custom tab is selec

Solution 1:

Actually, it's better to use a selector.

Here's a sample using Kotlin and the latest viewPager2 with tabLayout (based on Google's sample here):

        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            val tabView = LayoutInflater.from(this).inflate(R.layout.tab_with_badge, tabLayout, false)
            tabView.textView.text = "item$position" 
            tabView.badgeTextView.text = position.toString()
            tab.customView = tabView
        }.attach()

tab_with_badge.xml

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="horizontal"><androidx.appcompat.widget.AppCompatTextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/tab_color_selector"tools:text="@tools:sample/lorem" /><androidx.appcompat.widget.AppCompatTextViewandroid:id="@+id/badgeTextView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/badge_background"tools:text="12" /></LinearLayout>

tab_color_selector.xml

<selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:color="#f00"android:state_pressed="true" /><itemandroid:color="#0f0"android:state_selected="true" /><itemandroid:color="#00f" /></selector>

badge_background.xml

<shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><paddingandroid:left="4dp"android:right="4dp" /><solidandroid:color="@color/tab_color_selector" /><cornersandroid:radius="8dp" /></shape>

Solution 2:

You can do this programatically.

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

And then apply

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

Hope this solves your problem, more info can be found on link

In your case

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

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

Post a Comment for "Selected Custom Tab Text Color In Tablayout"