【问题标题】:Change <Button> color onClick?在单击时更改 <Button> 颜色?
【发布时间】:2014-04-13 17:03:17
【问题描述】:
<Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Add"
        android:id="@+id/btnAdd"
        android:background="#ff6347"
        android:textColor="#f8f8f8"
        android:layout_marginTop="36dp"
        android:clickable="true"
        android:layout_below="@+id/txtAddress"
        android:layout_centerHorizontal="true"
        android:focusable="true" />

这是我的 XML Button 元素,它很好而且很漂亮……但我希望它在被按下时被知道。我怎样才能让它在按下时和不按下时具有不同的样式?

【问题讨论】:

    标签: java android xml user-interface styling


    【解决方案1】:

    您可以使用选择器并为不同的状态使用可绘制对象。

    http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

    您也可以使用OnTouchListener 并在ACTION_DOWNACTION_UP 上为按钮设置颜色

    【讨论】:

      【解决方案2】:

      您想使用选择器作为按钮的背景。基本上你可以为按钮的每个状态定义你想要的不同形状,形状由颜色、圆角半径和其他很酷的东西组成。

      XML 文件保存在 res/drawable/button.xml:

      <?xml version="1.0" encoding="utf-8"?>
          <selector xmlns:android="http://schemas.android.com/apk/res/android">
              <item android:state_pressed="true"> <!-- pressed -->
                  <shape android:shape="rectangle" >
                      <solid android:color="@color/blue" />
                  </shape>
              </item>
              <item> <!-- default -->
                  <shape android:shape="rectangle" >
                      <solid android:color="@color/red" />
                  </shape>
              </item>
          </selector>
      

      此布局 XML 将可绘制的状态列表应用于 Button:

      <Button
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"
          android:background="@drawable/button" />
      

      【讨论】:

      • android:drawable。引用文档 可绘制资源。必需的。对可绘制资源的引用。 在您的示例选择器中没有
      猜你喜欢
      • 2015-08-06
      • 2023-04-03
      • 2012-12-06
      • 2019-10-03
      • 2018-10-25
      • 2014-09-30
      • 2021-07-07
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多