在Android设计库中使用TabLayout的图标选项卡

Tza*_*ich 10 android android-tabhost android-tabs android-design-library

我正在尝试在Android设计库中使用新的TabLayout创建仅带图标的应用栏.

像这样: 在此输入图像描述

如何使用新的TabLayout Android设计库来完成它.

有一个简单的解决方案,或者我必须只使用setCustomView.我试图避免使用它.因为我没有得到像上图这样的图标的色调颜色.

我试着像这样写:

tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_dashboard))
Run Code Online (Sandbox Code Playgroud)

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

Bud*_*ius 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>
Run Code Online (Sandbox Code Playgroud)

  • 对于遇到这个问题的新Android开发人员:这个文件应该保存在drawable目录中(例如`my_icon.xml`).并且可以像使用常规可绘制图标一样使用代码访问.(例如`R.drawable.my_icon`) (3认同)

Tza*_*ich -2

我是这样解决的:

色调_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"/>
Run Code Online (Sandbox Code Playgroud)

在你的java代码中

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

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