【问题标题】:Tab with icon using TabLayout in Android Design Library在 Android 设计库中使用 TabLayout 的带有图标的选项卡
【发布时间】:2015-08-29 23:47:38
【问题描述】:

我正在尝试使用 android 设计库中的新 TabLayout 来创建仅带有图标的应用栏。

像这样:

如何使用新的 TabLayout Android 设计库来做到这一点。

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

我试着这样写:

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

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

【问题讨论】:

  • 我没有使用过TabLayout,如果这没有帮助,请原谅我,但您是否尝试过使用TabLayout#setTabTextColors(int normalColor, int selectedColor)?我不确定它是否会给你想要的东西,但尝试设置它不会有坏处吗?

标签: android android-tabhost android-tabs android-design-library


【解决方案1】:

您必须为图标创建一个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>

【讨论】:

  • 对于遇到这个问题的新安卓开发者:这个文件应该保存在drawable目录中(例如my_icon.xml)。并且可以像普通的可绘制图标一样使用代码进行访问。 (例如R.drawable.my_icon)
  • @Manikanta 您已经为每个选项卡设置了多个图标状态,以便显示按下、聚焦等。选择器是维护图标之间关系的一种非常方便的方式。这种技术极大地简化了布局文件,因为它们只需要处理单个 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

【讨论】:

    【解决方案3】:

    我是这样使用它的: 如@Budius所示,在drawable中创建了一个xml文件。

    在代码中: tabLayout.getTabAt(0).setIcon(R.drawable.settings_tab_drawable);

    等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2015-11-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多