Android:在更改标签页时,在tabLayout中更改自定义标签视图

问题描述 投票:1回答:3

我正在尝试在切换选项卡时更改tabLayout选项卡中图标的颜色。我正在使用setCustomView(view)来设置这样的图标。

    View view = inflater.inflate(R.layout.layout_icon, null);
    view.findViewById(R.id.icon).setBackgroundResource(R.drawable.apple);

    TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setCustomView(view));

选择选项卡后,我想更改其图标的颜色,但我不知道该怎么做。如果我只是setCustomView(view)再次在选项卡上onTabSelected两个图标出现在选项卡中的不同颜色,这是原来的customView没有被删除。如何删除自定义视图?或者实现这个目标的方法是什么?有人可以请帮助。提前致谢 !!

android android-tablayout
3个回答
5
投票

刚刚解决了这个问题。您需要在CustomView中获得对ImageView的引用。然后我在OnTabSelectedListener中设置/取消设置颜色,如下所示:

@Override
public void onTabSelected(TabLayout.Tab tab)
{
    int tabIconColor = ContextCompat.getColor(getContext(), R.color.colorAccent);
    ImageView imageView = (ImageView)tab.getCustomView().findViewById(R.id.tab_icon);
    imageView.getBackground().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}

@Override
public void onTabUnselected(TabLayout.Tab tab)
{
    int tabIconColor = ContextCompat.getColor(getContext(), R.color.white_color);
    ImageView imageView = (ImageView)tab.getCustomView().findViewById(R.id.tab_icon);
    imageView.getBackground().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}

5
投票

所有人都要谨慎。

我花了很多时间在这个问题上,我希望这有助于某人:

方法TabLayout.Tab.setCustomView(View)的工作原理是添加更多对自定义视图的引用,而不是顾名思义,通过设置对一个自定义视图的单个引用。

您会认为如果您将此方法调用两次,则第一个引用将被第二个引用覆盖。但是,相反,它会将另一个视图添加到旧选项卡上方的选项卡中。你将无法看到它,因为标签不够高,但它就在那里。

这种方法更恰当地命名为TabLayout.Tab.addCustomView(View)

使用此布局的自定义视图时请记住这一点。如果由于某种原因最终调用该方法两次,当您调用tab.getCustomView().findViewById(id)时,您将收到与您期望的不同的引用。


2
投票

如果您有两个不同颜色的不同图标,则可以执行此操作。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tab_background_selected" android:state_selected="true" />
    <item android:drawable="@drawable/tab_background_unselected" android:state_selected="false" android:state_focused="false" android:state_pressed="false" />
</selector>
© www.soinside.com 2019 - 2024. All rights reserved.