【问题标题】:Android xml drawable color change on selected/focusedAndroid xml drawable color change on selected/focused
【发布时间】:2018-08-25 18:47:41
【问题描述】:

我创建了一个可绘制的 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>

结果图片:

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

【问题讨论】:

    标签: android xml-drawable


    【解决方案1】:

    您可以在&lt;selector&gt;下添加多个&lt;item&gt;s,并在&lt;item&gt;标签中指定状态作为属性。

    这里是语法

    <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"]/>
    

    【讨论】:

      【解决方案2】:

      试试这个:

      <?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>
      

      【讨论】:

      • 感谢您的回复,我试过这个代码它不起作用。
      • 它适用于可点击的按钮图像,但在这种情况下不适用。您还有其他建议吗?
      • 它适用于任何可以聚焦或选择的视图,这就是您所要求的。
      • 是的!但它不适用于已使用相同 xml 文件创建的可绘制形状!如您所说,它可以用于视图背景更改等。
      • 如果你知道答案对你没有用,为什么还要问这个问题?
      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 2022-12-28
      • 2015-08-03
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多