android tab selected color,android - Selected custom tab text color in TabLayout - Stack Overflow

在尝试创建带有徽章计数器的自定义TabLayout时,遇到一个问题:当自定义tab被选中时,TextView的颜色没有自动改变。为了解决这个问题,通过设置TextView的textColor,但需要找到正确且干净的方法。博客中提供了代码示例,展示了一个正确选择的默认tab和一个颜色不正确的自定义tab,并给出了修改TextView颜色的代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 selected, TextView color isn't changed automatically. How to achieve it in correct and clean way?

Properly selected default tab:

45cd6f59c82f5f310cf262b46e41f103.png

Wrong selected custom tab (text is grey but should be white):

6944c370545585995287a11ecba9f6e9.png

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

}

Layout

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

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

android:id="@+id/indicator"

android:layout_width="24dp"

android:layout_height="24dp"

android:background="@drawable/background_indicator"

android:gravity="center"

android:lines="1"/>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值