简体   繁体   中英

How to get Android Studio to check the background color of a button

I'm building an app using Java in Android Studio. I'm at the stage of writing an if-statement:

"If the background color of the button is white, turn the background color of the button to black."

Does anyone know the code to check if the background color button is white?

"if(button == white){}"

I only know the part on how to turn the background color button to black.

btnChangeColor.setBackgroundColor(getResources().getColor(R.color.black)

Thanks

A button view doesn't hold background color as a solid value. when you call setBackgroundColor, the given color value applies over the background drawable object( A Drawable is a graphic that can be drawn to the screen ) of the button. So you have to read the color value from this drawable.

    final int black = 0xFF000000;
    final int white = 0xFFffffff;

    button.setBackgroundColor(black);
    button.setTextColor(white);
    button.setText("Black");

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (((ColorDrawable) v.getBackground()).getColor() ==black) {
                button.setBackgroundColor(white);
                button.setTextColor(black);
                button.setText("White");
            } else {
                button.setBackgroundColor(black);
                button.setTextColor(white);
                button.setText("Black");
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM