0

I want to use a code that indicates the color of the button (id=button1) and do something if the color is blue, I mean =

if the color of button1 is blue type 1, if its green,yellow or other color, type game over.

how can i do it?

i tried this way:

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

there is an error:

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

and if you are hovering over the getColor() you get another error:

The method getColor() is undefined for the type ColorDrawable

what can I do? thx.

  • I agree with Gabe's answer.The method getColor() is only available in API 11(Honeycomb) and above. Refer http://stackoverflow.com/a/8089242/775467 – coderplus Jun 14 '14 at 16:56
  • I don't know how to do it.. im just a beginner and Gabe's answer is hard.. – user3731180 Jun 14 '14 at 17:11

2 Answers2

1

This is the wrong way to do it. You should never use UI attributes to determine program state, doing so leads to spaghetti code. Instead, you should have some variable in your code with a name that means something easily understood that tracks the state of the button. Whenever you change the color of the button, you set this variable. Then when you need to make some decision based on the color, you use this variable.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

You can also try something like set the color value as the tag like

android:tag="#ff0000"

And access it from the code

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

OR

Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138