【问题标题】:How To Change Color Of Drawable PNG Item in XML?如何更改 XML 中可绘制 PNG 项的颜色?
【发布时间】:2017-02-17 14:35:45
【问题描述】:

我有这个 xml 代码:

<item
    android:id="@+id/search_id"
    android:title="Search"
    app:showAsAction="always">
    <bitmap
        android:src="@drawable/ic_search_black_24dp"
        android:tint="@color/colorAccent">
    </bitmap>
</item>

<item
    android:id="@+id/shoppingcart_id"
    android:title="Shopping Cart"
    android:icon="@drawable/ic_shopping_cart_black_24dp"
    app:showAsAction="always"></item>

它们都是黑色图标,但我想将第一个图标更改为红色。但是当我运行我的应用程序时,它什么也没显示。是否可以仅使用 XML 更改可绘制资源中的 PNG 文件颜色而不在 java 中添加代码?

谢谢。

【问题讨论】:

标签: android xml


【解决方案1】:

编辑

糟糕,刚刚意识到您在谈论菜单图标,所以,只需尝试将您的位图包装在可绘制文件中,如下所述: https://stackoverflow.com/a/39535399/7296930


解决方案取决于您的 API 版本。

对于 API 21+:

尝试将图标定义为另一个带有色调的可绘制对象,并将这个新的可绘制对象引用为图标(而不是 标记)?

对于 API

只需遵循解决方案here,使用自定义 TintableImageView 和自定义属性。 您必须编写一些 Java 代码来定义 TintableImageView 小部件,但随后您的可绘制对象将仅在 xml 中定义,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <com.example.widgets.TintableImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        app:tint="@color/color_selector"/>

</LinearLayout>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多