java - 如何在按下按钮时动态更改图片并保存该图像的状态
问题描述
大家早上好。
我有一个问题,我需要在按下时更改图像,imageView
当Button
再次按下时更改为以前的图像。我什至设法通过 来做到这一点setBackgroundResource
,问题是当我关闭应用程序或退出该应用程序Activity
并返回到它时,图像又回到了android: background
从一开始就存在的那个。
有人能帮我吗?
PS我正在使用翻译器,如果我拼写错误,请见谅。
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();
}
推荐阅读
- python - Django表单字段不呈现
- java - 查找数组中的最大整数,在 Java 中具有指定的开始和结束索引,**递归**
- linux - 在makefile中更改PATH
- python-3.x - 在 Pytorch 内置的自定义 Batchnorm 中更新 running_mean 和 running_var 有问题吗?
- c#-4.0 - 这个 Entity Framework Core 异常是什么意思?
- r - 如何扩展您的绘图,以便可以看到所有标签而不会在 R 中重叠
- python - 链接:致命错误 LNK1104:无法使用 CMake 查找库打开文件“python38.lib”
- excel - Excel 中的“ActiveX 组件无法创建对象”错误
- angular - 当状态由ngrx-forms管理时,如何以角度动态地将formgroup控件添加到formarray?
- python - Selenium 似乎无法在页面上找到文本