Search code examples
javaandroidandroid-studioandroid-drawableandroid-color

Android Compare Background Color with Color


i am trying to make a little game.

There the Background color Randomly change from Blue to Green and back to Blue. If the user click the Blue "Button" then he lose.

My problem is how do i get the Background Color? and Compare it with R.color.colorGreen

I have tried some Examples from here but nothing works.

if(Integer.parseInt(button.getBackground().toString()) == R.color.colorBlue)

Solution

  • You should see this SO post.

    If you're on Android 3.0+ you can get the color value

    ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
    int color = buttonColor.getColor(); 
    

    So, your revised if statement would be

    ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
    int color = buttonColor.getColor();
    if (color == getResources().getColor(R.color.colorBlue)) {
        // if statement body
    }