Change tabs text color in TabLayout to different colors programmatically
Asked Answered
B

5

7

I have 7 dates tabs in my screen, when tab selected, the text is black in color; while other select-able tabs are white in color. If the date falls on another month, I want the text color to be grey color.

I assumed the first tab is 0, second tab is 1, and continues until 6. As in the picture, I want to change the text color of tab(3), tab(4), tab(5) and tab(6). How could it be done programmatically, when it meet required condition (not xml), to set the text color in these 4 tabs grey?

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/lblWeekMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/week"
        android:textAppearance="?attr/textAppearanceListItem" />
    <TextView
        android:id="@+id/lblWeekNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/lblWeekMsg"
        android:layout_alignBaseline="@id/lblWeekMsg"
        android:text=""
        android:textAppearance="?attr/textAppearanceListItem" />

</RelativeLayout>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="30">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/app_bar_layout">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@android:color/white"
            app:tabMode="scrollable"
            app:tabGravity="fill" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

I used this way to create tabs with fragment

public void setupViewPager(ViewPager viewPager, ArrayList<String> id, ArrayList<String> tasks,
                           ArrayList<Double> mondayHours, ArrayList<Double> tuesdayHours,
                           ArrayList<Double> wednesdayHours, ArrayList<Double> thursdayHours,
                           ArrayList<Double> fridayHours, ArrayList<Double> saturdayHours,
                           ArrayList<Double> sundayHours) {
    Bundle bundle = new Bundle();
    bundle.putStringArrayList(EXTRA_CHECKED_TASK_ID, id);
    bundle.putStringArrayList(EXTRA_CHECKED_TASKS, tasks);
    bundle.putSerializable(EXTRA_MONDAY, mondayHours);
    bundle.putSerializable(EXTRA_TUESDAY, tuesdayHours);
    bundle.putSerializable(EXTRA_WEDNESDAY, wednesdayHours);
    bundle.putSerializable(EXTRA_THURSDAY, thursdayHours);
    bundle.putSerializable(EXTRA_FRIDAY, fridayHours);
    bundle.putSerializable(EXTRA_SATURDAY, saturdayHours);
    bundle.putSerializable(EXTRA_SUNDAY, sundayHours);

    final String MON = "MON" + "\n" + MainActivity.sevenDatesList.get(0);
    final String TUE = "TUE" + "\n" + MainActivity.sevenDatesList.get(1);
    final String WED = "WED" + "\n" + MainActivity.sevenDatesList.get(2);
    final String THU = "THU" + "\n" + MainActivity.sevenDatesList.get(3);
    final String FRI = "FRI" + "\n" + MainActivity.sevenDatesList.get(4);
    final String SAT = "SAT" + "\n" + MainActivity.sevenDatesList.get(5);
    final String SUN = "SUN" + "\n" + MainActivity.sevenDatesList.get(6);

    adapter = new ViewPagerAdapter(getSupportFragmentManager(), bundle);
    adapter.addFragment(new MondayFragment(), MON);
    adapter.addFragment(new TuesdayFragment(), TUE);
    adapter.addFragment(new WednesdayFragment(), WED);
    adapter.addFragment(new ThursdayFragment(), THU);
    adapter.addFragment(new FridayFragment(), FRI);
    adapter.addFragment(new SaturdayFragment(), SAT);
    adapter.addFragment(new SundayFragment(), SUN);

    viewPager.setAdapter(adapter);
}

I had tried on this, but my code was not using tabWidget. I had tried on this too, but my code was not using tabHost.

My solution based on @Bhavesh Misri's suggestion:

ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
    //get number of tab
    int tabsCount = vg.getChildCount();
    //loop the tab
    for (int j = 0; j < tabsCount; j++) {
        //get view of selected tab
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);

        //when the day is not required to display - out of range
        if( j<lesserThan || j>largerThan ){
            //disable the selected tab
            vgTab.setEnabled(false);
            //set the not-required tab color transparent ratio
            vgTab.setAlpha((float) 0.50);
        } 
    }
Billfish answered 2/12, 2016 at 9:31 Comment(3)
Post your business logic where you are initializing and filling tab if possible.Interlunar
@PravinD Thanks for reminding, I added the code snippet.Billfish
Are you using any custom layout to render tab text? Also why you are adding fragments in adapter using custom method addFragment as override getItem(int position) already there in FragmentPagerAdapter for same purpose?Interlunar
O
9

Try this and let me know if this works for you:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
            if (tab.getPosition() == 0) {
                tabLayout.getTabAt(0).getIcon().setAlpha(255);
                tabLayout.getTabAt(1).getIcon().setAlpha(100);
                tabLayout.getTabAt(2).getIcon().setAlpha(100);
            } else if (tab.getPosition() == 1) {
                tabLayout.getTabAt(0).getIcon().setAlpha(100);
                tabLayout.getTabAt(1).getIcon().setAlpha(255);
                tabLayout.getTabAt(2).getIcon().setAlpha(100);

            } else if (tab.getPosition() == 2) {
                tabLayout.getTabAt(0).getIcon().setAlpha(100);
                tabLayout.getTabAt(1).getIcon().setAlpha(100);
                tabLayout.getTabAt(2).getIcon().setAlpha(255);

            }
        }

@Surya Prakash Kushawah your way is better.

Openwork answered 2/12, 2016 at 9:37 Comment(2)
your tabLayout.getTabAt(0).getIcon().setAlpha(100); gave me the clue, thanks a lot!Billfish
@CHANHAUYEEN Glad could help :)Openwork
A
9

set tab text color this way :

tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
Albaugh answered 2/12, 2016 at 9:46 Comment(1)
Thanks. This code will change text color for entire TabLayout. What I want is change single tab text color when it meet the condition.Billfish
I
3

Create a style in style.xml and call in xml layout like below

 <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">

        <item name="tabIndicatorColor">@color/colorAccent</item>
        <item name="tabIndicatorHeight">2dp</item>
        <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
        <item name="tabSelectedTextColor">@color/colorAccent</item>
    </style>

    <style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">@dimen/title_text_size</item>
        <item name="android:textColor">@color/secondaryText</item>
        <item name="textAllCaps">false</item>
        <item name="android:textStyle">normal</item>
    </style>

Call here

<android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabTextColor="@android:color/white"
                app:tabMode="scrollable"
      **style="@style/MyCustomTabLayout"**
                app:tabGravity="fill" />
Indevout answered 2/12, 2016 at 9:43 Comment(1)
I need to change text color based on certain condition, so I need it to be change in programmatically way.Billfish
B
0

The solution based on my code above:

ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
//get view of the 6th tab - start with zero
ViewGroup vgTabSixth = (ViewGroup) vg.getChildAt(5);
//set the not-required tab color transparent ratio 20%
vgTabSixth.setAlpha((float) 0.20);
Billfish answered 5/12, 2016 at 6:31 Comment(0)
P
0

Best practices is used material TabLayout with ViewPager2.

dependencies {
    // ...
    implementation 'com.google.android.material:material:1.0.0'
    // ...
}

In XML attributes

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_below="@+id/layout_toolbar">
            <com.google.android.material.tabs.TabLayout
                    android:id="@+id/tab_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabIndicatorColor="@color/white"
                    app:tabBackground="@color/colorAccent"
                    app:tabSelectedTextColor="@color/white"
                    app:tabTextColor="@color/white"
                    app:tabMode="scrollable" />
            <androidx.viewpager2.widget.ViewPager2
                android:id="@+id/view_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:nestedScrollingEnabled="false" />
        </LinearLayout>

In Kotlin

//set your adapter
//view_pager.adapter =  WebViewFragmentTabAdapter(supportFragmentManager, lifecycle)
TabLayoutMediator(tab_layout, view_pager) { tab, position ->
    tab.text = AppDataInstance.navigationTab[position].name
    view_pager.setCurrentItem(tab.position, true)
}.attach()

// in case you need to set color programmatically
(tab_layout as TabLayout).setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
(tab_layout as TabLayout).setSelectedTabIndicatorColor(ContextCompat.getColor(mContext, R.color.white))
(tab_layout as TabLayout).setTabTextColors(ContextCompat.getColor(mContext, R.color.white),
                ContextCompat.getColor(mContext, R.color.white))
Potluck answered 14/7, 2020 at 6:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.