【问题标题】:How to change the color of button after click?单击后如何更改按钮的颜色?
【发布时间】:2012-03-29 22:13:59
【问题描述】:

我创建了带有背景颜色的按钮,但是当我单击它时,它什么也不显示。
点击后我需要在按钮上显示不同的颜色,因为用户需要知道按钮是
点击。
我不明白该怎么做?
给我建议。
这是我的按钮代码。

<Button android:textSize="15px"
      android:id="@+id/button9" 
      android:gravity="center|bottom" 
      android:textColor="@color/myWhiteColor" 
      android:drawableTop="@drawable/math"
      android:text="@string/HomePage_Math" 
      android:background="@color/myMaroonColor" 
      android:layout_width="54dp" 
      android:layout_height="wrap_content" ></Button>

【问题讨论】:

标签: android button click


【解决方案1】:

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

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#ffff0000"/> <!-- pressed -->
    <item android:state_focused="true"
          android:color="#ff0000ff"/> <!-- focused -->
    <item android:color="#ff000000"/> <!-- default -->
</selector>

//这个布局XML会将颜色列表应用到一个View:

<Button android:textSize="15px"
      android:id="@+id/button9" 
      android:gravity="center|bottom" 
      android:textColor="@color/myWhiteColor" 
      android:drawableTop="@drawable/math"
      android:text="@string/HomePage_Math" 
      android:background="@drawable/button_bg" 
      android:layout_width="54dp" 
      android:layout_height="wrap_content" ></Button>

【讨论】:

  • 它显示错误“tts 应用程序已意外停止”...不工作
  • @sandiparmal 将该 xml 保存在您的可绘制文件夹中并尝试使用 android:background="@drawable/button_bg"。
  • @sandiparmal 此错误与此代码无关。它在您的应用程序中出现不同的错误。
  • @SandipArmalPatil 如果您在 button_bg xml 中使用可绘制而不是颜色代码,那么您将不会收到此错误“应用程序已意外停止”
  • 标签需要一个 'drawable' 属性或定义可绘制对象的子标签。这段代码行不通
【解决方案2】:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
    <item android:state_focused="true" android:drawable="@android:color/holo_green_dark" />
    <item android:drawable="@color/colorCartButton" />
</selector>

这会起作用

【讨论】:

  • 为什么会起作用?添加一些额外的细节,使其成为一个很好的答案。
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2021-03-18
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2019-05-20
相关资源
最近更新 更多