Kurlicue Kurlicue - 6 months ago 8
Android Question

Android: checking a view's background

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

subject_button
)

What I want to do:

When I click one button his background changes ( to
clicked_subject
), 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
clicked_subject
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:

theButton1.setBackgroundResource(R.drawable.subject_button);
theButton1.setOnClickListener(this);
//same for other 2

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

theButton1.setBackgroundResource(R.drawable.subject_button);
theButton2.setBackgroundResource(R.drawable.subject_button);
theButton3.setBackgroundResource(R.drawable.subject_button);

v.setBackgroundResource(R.drawable.clicked_subject);

} else {

v.setBackgroundResource(R.drawable.subject_button);
}


Why is this happening?

Answer

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)