在Android Design Library中使用TabLayout创建带有图标的选项卡。

10

我正在尝试使用Android Design Library中的新TabLayout创建仅包含图标的应用栏。

就像这样: enter image description here

我该如何使用新的TabLayout Android Design Library来实现它。

是否有简单的解决方案,或者我只能使用setCustomView。我试图避免使用它,因为我没有得到像上面图片中一样的图标颜色。

我尝试写成这样:

tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_dashboard))

但是当我选择选项卡时,图标仍然保持相同的颜色


我并没有经常使用TabLayout,所以如果这不是很有帮助,请原谅。但是你尝试过使用TabLayout#setTabTextColors(int normalColor, int selectedColor)吗?我不确定它是否能给你想要的结果,但是尝试设置一下也无妨。 - Joseph Roque
3个回答

9

您需要为图标创建一个选择器。例如:

selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_dashboard_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/ic_dashboard_selected"
          android:state_selected="true" />
    <item android:drawable="@drawable/ic_dashboard_normal" />
</selector>

3
对于新的Android开发者,如果遇到这个问题:这个文件应该保存在drawable目录下(例如my_icon.xml)。可以像使用常规可绘制图标一样通过代码访问它(例如R.drawable.my_icon)。 - ntsh
1
@Manikanta,你已经为每个选项卡设置了多个图标状态,以显示按下、聚焦等状态。选择器是一种非常方便的方式,可以维护图标之间的关系。这种技术极大地简化了布局文件,因为它们只需要处理单个drawable选择器,而不需要知道不同的状态。 - Richard Le Mesurier

1
我是这样使用的: 按照@Budius的示例,在drawable中创建了一个xml文件。
在代码中: tabLayout.getTabAt(0).setIcon(R.drawable.settings_tab_drawable); 等等。

-2

我是这样解决的:

tint_tab.xml

<com.hannesdorfmann.appkit.image.TintableImageView
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 app:tint="@color/tab_color_selector"/>

在你的Java代码中

TintableImageView tab1 = (TintableImageView) LayoutInflater.from(this).inflate(R.layout.tint_tab, null);
tab1.setImageResource(R.drawable.ic_dummy);
mTabLayout.getTabAt(0).setCustomView(tab1)

参考: https://github.com/sockeqwe/appkit/blob/master/image/src/main/java/com/hannesdorfmann/appkit/image/TintableImageView.java


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接