大家早上好。
我遇到一个问题,当按下 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/