android - 如何使用 sharedPreferences 保存背景
问题描述
你好朋友我用微调器改变了背景,但我不能用共享偏好保存背景你能帮我吗?但是如果我删除位置的 .setBackgroundColor() ,即时背景不会改变,我真的不明白。代码就是全部。我无法保存此 SharedPreence 的颜色代码。顺便说一句,我是 ANDROID 的新手。
公共类 MainActivity 扩展 AppCompatActivity {
ConstraintLayout tasarım;
private SharedPreferences sharedPreferences;
private Spinner spinner;
private ArrayList<String> renkler = new ArrayList<>();
private ArrayAdapter<String> veriAdaptoru;
String color;
tasarım=(ConstraintLayout)findViewById(R.id.tasarım);
spinner = findViewById(R.id.spinner);
renkler.add("beyaz");
renkler.add("mavi");
renkler.add("kırmızı");
renkler.add("yeşil");
veriAdaptoru = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, renkler);
spinner.setAdapter(veriAdaptoru);
sharedPreferences = this.getSharedPreferences("com.example.sondev", MODE_PRIVATE);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
String colorSec="";
if (position==0){
tasarım.setBackgroundColor(Color.WHITE);
colorSec="WHITE";
editor.putString("colour",colorSec);
editor.commit();
}
else if (position==1){
tasarım.setBackgroundColor(Color.BLUE);
colorSec="BLUE";
editor.putString("colour",colorSec);
editor.commit();
}
else if(position==2){
tasarım.setBackgroundColor(Color.RED);
colorSec="RED";
editor.putString("colour",colorSec);
editor.commit();
}else if (position==3){
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
else {
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
color=prefs.getString("colour","WHITE");
if (color.equals("BLUE")){
tasarım.setBackgroundColor(Color.BLUE);
}
else if(color.equals("RED")){
tasarım.setBackgroundColor(Color.RED);
}else{
tasarım.setBackgroundColor(Color.GREEN);
}
解决方案
推荐阅读
- python - 维基百科抓取模棱两可的结果
- python - 字符串索引必须是整数 json
- android - ConstraintLayout:如何以编程方式将屏幕划分为屏幕高度的两个相等部分
- entity-framework - EF Core 更新无法翻译 LINQ 表达式“x”
- swiftui - SwiftUI 中的 WKWebView 未在 macOS 上加载 HTML 字符串
- python - 如何一次性安装我所有的 python 模块
- javascript - 单击列表项时根据数据位置名称添加额外的类?
- r - 当情节显示每月频率的时间序列时如何从时间序列中获取年份(Rbeast)
- assembly - 当我要检查包括寄存器在内的数据时,为什么 x 命令显示“无法将值转换为整数”?
- jsdoc - jsdoc - 记录嵌套数组参数