如何更改 TabLayout 所选选项卡的图标颜色? [英] How do I change the color of icon of the selected tab of TabLayout?

查看:46
本文介绍了如何更改 TabLayout 所选选项卡的图标颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 TabLayoutViewPager 一起使用,我想知道如何最有效地更改 TabLayout 中所选选项卡的图标颜色.

I'm using a TabLayout with a ViewPager and I'm wondering how I can most efficiently change the color of the icon of the selected tab in the TabLayout.

Google 的 Youtube 应用是关于如何实现这一点的完美参考.在主页面上,有四个深灰色图标.选择特定选项卡后,该选项卡的图标变为白色.

A perfect reference for how this is implemented is Google's Youtube app. On the main page, there are four icons that are colored dark gray. When a specific tab is selected, the tab's icon becomes white.

没有任何第三方库,如何达到同样的效果?

Without any third party libraries, how can I achieve the same effect?

一种可能的解决方案显然是使用选择器.但在这种情况下,我必须找到图标的白色和灰色版本,然后在选项卡被选中或取消选中时切换图标.我想知道是否有更有效的方法可以突出显示图标颜色或其他东西.我在任何教程中都找不到这个.

One possible solution is apparently with selectors. But in that case, I would have to find both a white and a gray version of the icon and then switch the icon when the tab becomes selected or deselected. I'm wondering if there's a more effective method where I can just highlight the icon color or something. I haven't been able to find this in any tutorial.

编辑

我在上面直接提到的解决方案需要为每个选项卡的图标使用两个可绘制对象.我想知道是否有一种方法可以通过每个选项卡的图标的 ONE drawable 以编程方式完成.

The solution that I mention directly above requires the use of two drawables for each tab's icon. I'm wondering if there's a way I can do it programmatically with ONE drawable for each tab's icon.

推荐答案

我找到了一种简单的方法.

I found a way that can be easy.

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(
            new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {

                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    super.onTabSelected(tab);
                    int tabIconColor = ContextCompat.getColor(context, R.color.tabSelectedIconColor);
                    tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    super.onTabUnselected(tab);
                    int tabIconColor = ContextCompat.getColor(context, R.color.tabUnselectedIconColor);
                    tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {
                    super.onTabReselected(tab);
                }
            }
    );

这篇关于如何更改 TabLayout 所选选项卡的图标颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆