简体   繁体   中英

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

Good morning people.

I have a problem where I need to change an image of an 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 application or exit that particular Activity and return to it the image is back to the one that was in android: background from the beginning.

Can someone help me?

PS I'm using the translator, sorry if I have something spelled wrong.

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 (status == 0){ 
            imgStatus.setBackgroundResource(R.drawable.ic_on);
            status = 1;
        }else{
            imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
            status = 0;                   
        }
    }
});

}

Try doing it this way. You need to save the state yourself.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

String status = preferences.getInt("status", 0);

In your onClicklistener

if (status == 0){ 
        imgStatus.setBackgroundResource(R.drawable.ic_on);
        editor.putInt("status", 1);
    }else{
        imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
        editor.putInt("status", 0);            
    }
   editor.apply();
}

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