android - Is it possible to save void in SharedPreferences
问题描述
I have a button which changes the color of the MainActivity
but this works only if the app it is open if I exit the app and open again it return to normal color which is white.
How to store with Shared Preferences do you have any idea how to do that because strings, int and boolean I can save but this function I don' have any idea.
This is my code.
MainActivity.class
public static final String Change_Color = "Change_Color";
private boolean switchOnOff;
setContentView(R.layout.activity_main);
if (switchOnOff == true) {
setColorGreyImageButton();
} else if(switchOnOff == false) {
setColorWhiteImageButton();
}
if(id == R.id.menu_back_white) {
saveColor();
} else if (id == R.id.menu_back_black) {
saveColor2();
}
public void setColorGreyImageButton() {
settings.setColorFilter(Color.parseColor("#757575"));
voiceSearch.setColorFilter(Color.parseColor("#757575"));
share.setColorFilter(Color.parseColor("#757575"));
search.setColorFilter(Color.parseColor("#757575"));
mainView.setBackgroundColor(Color.parseColor("#FFFFFF"));
SharedPreferences in MainActivity
public void saveColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, false);
switchOnOff = sharedPreferences.getBoolean(Change_Color, false);
}
public void saveColor2() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, true);
switchOnOff = sharedPreferences.getBoolean(Change_Color, true);
}
解决方案
Use these methods in your activity class:
private boolean getChangeColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
return sharedPreferences.getBoolean(getPackageName() + ".change_color", false);
}
private void saveChangeColor(boolean changeColor) {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getPackageName() + ".change_color", changeColor);
editor.apply();
}
In onCreate()
check the boolean
value stored in SharedPreferences
:
switchOnOff = getChangeColor();
if (switchOnOff) {
setColorGreyImageButton();
} else {
setColorWhiteImageButton();
}
and when you want to change the value in SharedPreferences
call:
saveChangeColor(true);
or
saveChangeColor(false);
推荐阅读
- php - 在 Laravel 中 queue:work 和 config/queue.php 传递的参数之间的区别
- javascript - JavaScript scrollBy(x,y) 不适用于 Android WebView 中的样式列宽
- kubernetes - 只能通过 HTTP 而不是 HTTPS 访问我的应用程序
- c# - 由于计时和线程问题,NUnit 测试执行失败
- php - PHP上传本地文件无按钮
- reactjs - 在反应中触发 NavLink 上的焦点()
- python - 使用 dataframe.at 时浮点数被舍入,而不是 dataframe.iloc
- javascript - setInterval 和 setTimeout 中的间隔不准确
- asciidoc - 如何为现有的 Asciidoctor Asciidoc 宏创建自定义 HTML 输出?
- java - 来自 SQL 数据库的带有时间的 JFreechart 图表