0

I want when a button is clicked to get it's background color.If the background color is the same with a color in resources named "blue_color", make background transparent.Else make it "blue_color". I have tried the method mentioned here but it gives me the error.

Code:

    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
                ColorDrawable btc = (ColorDrawable) btn.getBackground();
                int colorId = btc.getColor();
                if(colorId == R.color.blue_color){
                btn.setBackgroundColor(Color.TRANSPARENT);
               }else{
               btn.setBackgroundColor(getResources().getColor(R.color.blue_color));
               }
             }
   });

error from logcat:

FATAL EXCEPTION: main java.lang.ClassCastException: android.graphics.drawable.InsetDrawable cannot be cast to android.graphics.drawable.ColorDrawable

in the line where is

ColorDrawable btc = (ColorDrawable) btn.getBackground();

Community
  • 1
  • 1
  • The color will never be `R.color.blue_color`, because `R.color.blue_color` is not a color. It is an identifier of a color resource. I suggest that you use a separate `boolean` or other field to track the state of your button. – CommonsWare Nov 12 '16 at 13:23

1 Answers1

0

You should use btn.getBackground().getColor();

In your code you are getting a drawable... So the line should be:

ColorDrawable btc = (ColorDrawable) btn.getBackground().getColor();

Edit: You can get an int id of the color from resources like this:

int alpha = ... // 0-255
int blueColor = ResourcesCompat.getColor(getResources(), R.color.blue_color, null);
int blueColorWithAlpha = Color.argb( 
alpha, 
Color.red(blueColor), Color.green(blueColor), Color.blue(blueColor) );

The id of the color is now blueColorWithAlpha so you can compare it with the one of the button.. To get the color id of the button you can do so: int color = ((ColorDrawable)button.getBackground()).getColor();

I haven't tested this code but did some search and found these snippets on stackoverflow...

Asama
  • 385
  • 2
  • 14
  • I can't use ColorDrawable btc = (ColorDrawable) btn.getBackground().getColor(); There is a message saying "Cannot resolve method 'getColor" –  Nov 12 '16 at 13:24
  • Try this: Drawable background = btn..getBackground(); if (background instanceof ColorDrawable) { Color color = ((ColorDrawable) background).getColor(); } – Asama Nov 12 '16 at 13:27
  • Required android.graphics.Color , found int in Color color = ((ColorDrawable) background).getColor(); –  Nov 12 '16 at 13:33