android - 使用 ColorStateList 色调值膨胀 ImageView/ImageButton 时出错

标签 android imageview android-appcompat android-4.4-kitkat tint

ImageView/ImageButton (AppCompatImageView/AppCompatImageButton) 与 的样式属性结合使用使用 ColorStateList 资源的 >android:tint 在 >= API 21 上工作正常,但在 API < 21 上抛出 InflateException

首先,我什至不知道 AppCompatImageView/(Button) 着色是否支持 ColourStateList xml 资源作为 android:tint 值,我似乎无法找到明确的答案。我可以在 S/O 上找到的建议是实现 TintableImageView 等,但这些答案已经过时了,而且从 appcompat 实现的来源看来,这应该是一个功能。

澄清这绝对是问题所在。删除 android:tint 属性或将其设置为单一颜色资源即可。

还要澄清一下,我知道这可以通过编程方式实现。我试图让它在 xml 中向后兼容。

最小示例

activity_foo.xml

<android.support.v7.widget.AppCompatImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_caret_up"
                style="@style/IconButton.Primary"

/>

样式.xml

<style name="IconButton.Primary">
    <item name="android:tint">@color/link_button_color</item>
</style>

link_button_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:color="@color/btnLinkPressedTextColor"
      android:state_selected="true" />
  <item android:color="@color/btnLinkPressedTextColor"
      android:state_pressed="true" />
  <item android:color="@color/btnLinkTextColor" />

</selector>

最佳答案

在我的例子中,我将 android:tint 替换为 app:tint 并添加到根元素 xmlns:app="http://schemas.android. com/apk/res-auto”。它修复了 API 级别 < 21 的崩溃问题。

颜色状态选择器 /res/color/color_selector.xml 看起来像:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#151515"/>
    <item android:state_focused="true" android:color="#151515"/>
    <item android:color="#424242"/>
</selector>

关于android - 使用 ColorStateList 色调值膨胀 ImageView/ImageButton 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43800867/

相关文章:

android - YouTube Android Player API 在新的 YouTube 版本中抛出 "BadParcelableException ClassNotFoundException when unmarshalling: asc"

android - 在线性布局中拖放图像

带有 WhatsApp 图标的 Android 工具栏后退箭头

android-5.0-lollipop - ActionBar 中动画 ActionBarDrawerToggle 的颜色

android - Android在TextView中为一组数字设置动画,就像在纺车上一样

android - 如何处理自定义 android View /小部件的可见性更改

java - 使用 Chaquopy 在 Android 中自写 python 代码

android - 如何在imageview中查看下一张图片?

java - Android - 自定义 ImageView,带有勾选标记图像为选定状态

android - OnResume/OnPause 被多次调用