以编程方式将 TabLayout 中的选项卡文本颜色更改为不同的颜色

Change tabs text color in TabLayout to different colors programmatically

我的屏幕上有 7 个日期标签,当标签 selected 时,文本是黑色的;而其他 select-able 选项卡是白色的。如果日期是另一个月,我希望文本颜色为灰色。

我假设第一个选项卡是 0,第二个选项卡是 1,一直持续到 6。 如图所示,我想改变tab(3)、tab(4)、tab(5)和tab(6)的文字颜色。当满足要求的条件(不是xml)时,如何以编程方式将这 4 个选项卡中的文本颜色设置为灰色?

<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>

我用这种方式创建了带有片段的标签

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);
}

我试过 this,但我的代码没有使用 tabWidget。 我也试过 this,但我的代码没有使用 tabHost。

我的解决方案基于@Bhavesh Misri 的建议:

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);
        } 
    }

试试这个,让我知道这是否适合你:

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 你的方法更好。

在 style.xml 中创建样式并调用 xml 布局,如下所示

 <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>

在这里打电话

<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" />

以这种方式设置选项卡文本颜色:

tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));

基于我上面代码的解决方案:

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);

最佳做法是 material TabLayoutViewPager2

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

在XML属性中

<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>

在 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))