【问题标题】:Get the color of the button获取按钮的颜色
【发布时间】:2014-08-05 00:06:09
【问题描述】:

我想使用指示按钮颜色的代码 (id=button1) 并在颜色为蓝色时执行某些操作, 我的意思是=

如果button1的颜色是蓝色类型1,如果是绿色、黄色或其他颜色,输入game over。

我该怎么做?

我试过这样:

if(v.getId() == R.id.button1){
          ColorDrawable buttonColor = (ColorDrawable) button1.getBackground();
          int colorId = buttonColor.getColor();
      }

有一个错误:

Multiple markers at this line
- Type mismatch: cannot convert from ColorDrawable to int
- The method getColor() is undefined for the type 

如果您将鼠标悬停在 getColor() 上,则会出现另一个错误:

The method getColor() is undefined for the type ColorDrawable

我能做什么? 谢谢。

【问题讨论】:

  • 我同意 Gabe 的回答。getColor() 方法仅在 API 11(Honeycomb) 及更高版本中可用。参考stackoverflow.com/a/8089242/775467
  • 我不知道该怎么做..我只是一个初学者,加布的答案很难..

标签: android


【解决方案1】:

这是错误的做法。你永远不应该使用 UI 属性来确定程序状态,这样做会导致意大利面条式代码。相反,您应该在代码中包含一些变量,其名称意味着易于理解的跟踪按钮状态的名称。每当您更改按钮的颜色时,都会设置此变量。然后,当您需要根据颜色做出一些决定时,您可以使用此变量。

【讨论】:

  • 你能说得更具体些吗?这是我在做的第一个应用程序,你能给我一个方法吗?
【解决方案2】:

您也可以尝试将颜色值设置为标签,例如

android:tag="#ff0000"

并从代码中访问它

String colorCode = (String)btn.getTag();

Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 2016-08-12
    • 2011-12-26
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    相关资源
    最近更新 更多