How to change an image dynamically when a button is pressed and save the state of that image

Asked

Viewed 171 times

1

I have a problem where I need to alter an image of a imageView when the Button is pressed and when it is pressed again change to the image that was previously. I even managed to do this through the setBackgroundResource, the problem is when I close the app or get out of this determined Activity and I go back to her the image returns to be the one that was in android:background from the start. Can someone help me?

Xml code

<Button
    android:id="@+id/buttonLigarDesligar"
    android:padding="10dp"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="@drawable/icone_ligar"/>


<ImageView
    android:id="@+id/imgStatus"
    android:padding="10dp"
    android:background="@drawable/icone_vermelho"
    android:layout_width="40dp"
    android:layout_height="40dp"/>

Java code

buttonLigarDesligar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int status = 0;

            if (satus == 0){ 
                imgStatus.setBackgroundResource(R.drawable.ic_on);
                status = 1;
            }else{
                imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
                status = 0;                   
            }
        }
    });
}
  • You can store this information in a database, or ideally save it in a sharedpreferences, if no one answers you by tomorrow, I’ll help. Pq now to off pc

1 answer

1


You can use Sharedpreferences to save user information to do the following:

First within your Activity declare:

private SharedPreferences sharedPreferences;
private boolean statusOff;
public static final String SHARED_PREFERENCES_USER = "user_preferences";
public static final String BUTTON_ON_OFF = "button_on_off";

Within the onCreate method add:

    sharedPreferences = this.getSharedPreferences(SHARED_PREFERENCES_USER, Context.MODE_PRIVATE);
    //Caso ainda não tenha sido criada essa preferência o retorno booleano
    //sera true, como destacado embaixo
    statusOff = sharedPreferences.getBoolean(BUTTON_ON_OFF, true);

Leave your button click event like this:

buttonLigarDesligar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences.Editor editor = sharedPreferences.edit();

                if (statusOff) {
                    imgStatus.setBackgroundResource(R.drawable.ic_on);
                    //agora o valor do sharedpreferences é true, ou seja está ligado.
                    editor.putBoolean(BUTTON_ON_OFF, false);
                } else {
                    //caso o sharedpreference for false, então altera o icone pra vermelho e o valor
                    //booleano passa a ser true.
                    imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
                    editor.putBoolean(BUTTON_ON_OFF, true);
                }
                editor.apply();
            }
        });

Within your Activity rewrite the onResume method as follows:

@Override
protected void onResume() {
    super.onResume();
    //Para quando a aplicação, for pausada ou parada, o método onResume checará
    //o status do botão que está salvo e caso ele seja "false" então altera
    //o seu background para o ic_on. Caso statusOff seja "true", não tem necessidade
    //de alteração já que você definiu por padrão no xml "icone_vermelho"
    if (!statusOff) {
        imgStatus.setBackgroundResource(R.drawable.ic_on);
    }
}

I hope I’ve helped.

  • 1

    Mt thanks guy, I managed to solve here,I did not know about sharedpreferences kkk, I’m new on android, but again thank you!

Browser other questions tagged

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