Android XML可绘制颜色在选定/集中显示的颜色上的变化

时间:2018-08-25 18:47:42

标签: android xml-drawable

我创建一个可绘制的xml文件,以使用以下代码绘制一条线。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="line">
            <solid android:color="@color/colorPrimary" />
            <size android:width="100dp" android:height="50dp" />
            <stroke android:width="5dp" android:color="@color/colorPrimary" />
        </shape>
    </item>

</selector>

结果图片: enter image description here

我想在选择或聚焦时更改此图像的颜色。我怎样才能做到这一点?任何指导将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

尝试一下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <shape android:shape="line" >
            <solid android:color="@color/newcolor" />
            <size android:width="100dp" android:height="50dp" />
            <stroke android:width="5dp" android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="line" >
            <solid android:color="@color/newcolor" />
            <size android:width="100dp" android:height="50dp" />
            <stroke android:width="5dp" android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item>
        <shape android:shape="line">
            <solid android:color="@color/colorPrimary" />
            <size android:width="100dp" android:height="50dp" />
            <stroke android:width="5dp" android:color="@color/colorPrimary" />
        </shape>
    </item>

</selector>

答案 1 :(得分:0)

您可以在<item>下添加多个<selector>,并在<item>标签中将状态指定为属性。

这是语法

<item
    android: state_pressed = ["true" | "false"]
    android: state_focused = ["true" | "false"]
    android: state_hovered = ["true" | "false"]
    android: state_selected = ["true" | "false"]
    android: state_checkable = ["true" | "false"]
    android: state_checked = ["true" | "false"]
    android: state_enabled = ["true" | "false"]
    android: state_activated = ["true" | "false"]
    android: state_window_focused = ["true" | "false"]/>