Kurlicue Kurlicue - 1 year ago 63
Android Question

Android: checking a view's background

I have 3 buttons, all of them have the same background drawable by default (


What I want to do:

When I click one button his background changes ( to
), all the others remain with the default background, if I click one button after clicking another, the button I just clicked changes his background while the previous one gets back to the initial background, allowing only one button to have the
background, if the diffrent button gets clicked again his background goes back to the initial one, leting all the buttons with the initial background.

The problem:

If I click the diffrent button, his background remains the same instead of changing back to the initial one.

My logic:

//same for other 2

public void onClick(View v) {
if (v.getBackground() == ContextCompat.getDrawable(this, R.drawable.subject_button)) {



} else {


Why is this happening?

Answer Source

I solved it by instead of changing only the background color on clicking the button, I also change the textColor, then I can check the textColor with if (((Button) v).getCurrentTextColor() == Color.WHITE)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download