gpt4 book ai didi

java - 如何在按下按钮时动态更改图片并保存该图像的状态

转载 作者:行者123 更新时间:2023-12-02 03:02:14 26 4
gpt4 key购买 nike

大家早上好。

我遇到一个问题,当按下 Button 时,我需要更改 imageView 的图像,并在再次按下时更改为之前的图像。我什至设法通过 setBackgroundResource 来做到这一点,问题是当我关闭应用程序或退出该特定的 Activity 并返回到它时,图像又回到了原来的状态从一开始就在android:background中。

有人可以帮助我吗?

附注我正在使用翻译器,如果拼写错误,请抱歉。

Xml代码

<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代码

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;
}
}
});

}

最佳答案

尝试这样做。你需要自己拯救国家。

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

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

在你的 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();
}

关于java - 如何在按下按钮时动态更改图片并保存该图像的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com