首页 > 解决方案 > 如何使用 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);
    }

标签: androidbackgroundsharedpreferencesspinnerbackground-color

解决方案


推荐阅读