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

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

问题描述

我正在使用带有 ViewPager TabLayout ,我想知道如何才能最有效地更改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.

编辑

我上面直接提到的解决方案需要为每个标签的图标使用两个drawable。我想知道是否有一种方法可以通过编程方式对每个标签的图标进行 ONE 绘制。

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天全站免登陆