【问题标题】:How to put an attr inside a custom drawable?如何将 attr 放入自定义可绘制对象中?
【发布时间】:2017-01-26 19:59:34
【问题描述】:

我在尝试将 attr 放入自定义可绘制 xml 时遇到问题。

这是我的布局示例:

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/my_custom_btn"/>

然后我的自定义drawable“my_custom_btn”,我想用attr_my_custom_color指定它的颜色:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
            android:drawable="?attr/attr_my_custom_color" /> <!-- pressed -->
    </selector>

我的 attr.xml 文件:

<resources>
     <attr name="attr_my_custom_color" format="color"/>
</resources>

我的 style.xml 文件,我的应用程序正在使用这个主题(在我的清单中):

<resources>
<style name="AppThemeTest" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="attr_my_custom_color">@color/primary</item>

</style>

当我在我的布局中测试它时,我的 attr 工作正常,但是当我把它放在我的自定义可绘制对象中时,它就不起作用了。

它编译得很好,但是当我启动我的应用程序时,它会显示以下错误:

原因:org.xmlpull.v1.XmlPullParserException:二进制 XML 文件第 4 行:标签需要 'drawable' 属性或定义可绘制对象的子标签

您能帮我在自定义可绘制对象中指定一个属性吗?

【问题讨论】:

    标签: android xml styles drawable attr


    【解决方案1】:
    you have to change background to drawable
    
    
    <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawable ="@drawable/my_custom_btn"/>
    

    【讨论】:

    • 它不再崩溃,但它也不适用于&lt;item android:state_pressed="true" android:drawable="?attr/attr_my_custom_color" /&gt; &lt;!-- pressed --&gt;
    • 你的 minSdkVersion 是多少?
    • 如果我应用标准颜色&lt;item android:drawable="@color/highlight" /&gt;,它也不会应用颜色
    • 请更改 thr minSdkVersion 21 然后检查。之后我会给你正确的答案
    • 我只能使用 minSdkVersion 19。我无法检查 21。您的正确答案是否意味着使用 minSdkVersion 21?
    猜你喜欢
    • 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
    相关资源
    最近更新 更多