Change background when clicking and then return the original color

Asked

Viewed 559 times

0

I’m having a hard time at the moment when I select several Textview, I can change the color normally and return when the id is the same as the one selected.

My problem is this:

When I change the background color of several in a row it is normal, but if I need to change the penultimate color or any other without being the last button I changed the background it is necessary that I click twice. I need the first click to change the background.

My code is as follows:

@SuppressLint("ResourceAsColor")
public String buttonballsClick(View button){
    String tag = (String)button.getTag();
    int numeroInteiro = Integer.parseInt(tag);

    switch (numeroInteiro) {
        default:
            if (games.selectedTag == null || games.selectedTag != tag){
                button.setBackgroundResource(R.mipmap.botao_lotecaa);
                games.setActualNumber(tag);
                games.selectedTag = tag;
            }
            else if (games.selectedTag.equals(tag)) {
                button.setBackgroundResource(R.mipmap.botao_loteca);
                games.selectedTag = null;
            }
            else {
                Toast.makeText(ActivityLotecaCreateGame.this, "Houve um problema: " + tag, Toast.LENGTH_LONG).show();
            }
            break;
    }
    return tag;
}

1 answer

1

Hello, Edi!

If I understand your problem correctly, you need that when you click the previous background color back on the button again. So, do it this way

1 - Create a selector for each button, if you share different states, in the directory drawables

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Um drawable para o estado de pressionado -->
    <item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
    <!-- Um drawable para o estado normal do botão -->
    <item android:drawable="@drawable/button_bg_normal"></item>

</selector>

2 - Add the selector to their buttons

<Button
   android:id="@+id/id_do_seu_botao"
   android:background="@drawable/selector_para_esse botao"
   android:layout_width="200dp"
   android:layout_height="126dp"
   android:text="Play" />

Using this, you abstract the work of making the exchange of background and avoids possible memory overloads.

I hope this helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.