gpt4 book ai didi

java - SharedPreferences 编辑保存

转载 作者:太空狗 更新时间:2023-10-29 14:56:26 24 4
gpt4 key购买 nike

这是我的设置菜单,它是一系列的 9 个图像按钮,可以根据偏好更改图像。当按下图像按钮时,它应该更改首选项的 boolean 值,以便另一个 Activity 可以相应地采取行动。

目前它根据默认值填充图像按钮,但在设置菜单中所做的更改似乎不是永久性的。

public class SettingsActivity extends PreferenceActivity {
ImageButton[] level = new ImageButton[9];

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);

level[0] = (ImageButton) findViewById(R.id.imageButton);
level[1] = (ImageButton) findViewById(R.id.imageButton2);
level[2] = (ImageButton) findViewById(R.id.imageButton3);
level[3] = (ImageButton) findViewById(R.id.imageButton4);
level[4] = (ImageButton) findViewById(R.id.imageButton5);
level[5] = (ImageButton) findViewById(R.id.imageButton6);
level[6] = (ImageButton) findViewById(R.id.imageButton7);
level[7] = (ImageButton) findViewById(R.id.imageButton8);
level[8] = (ImageButton) findViewById(R.id.imageButton9);

PopulateButtons();

}

public void PopulateButtons(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
for (int i = 0; i < 9; i++) {
String prefKey = String.format("lev%s", i);
System.out.println(prefKey);
if (preferences.getBoolean(prefKey, false) == true) {
level[i].setBackgroundResource(R.mipmap.settings_verbs);
level[i].setOnClickListener(mySettingsHandler);
} else {
level[i].setBackgroundResource(R.mipmap.ic_launcher);
level[i].setOnClickListener(mySettingsHandler);
}

}
}


View.OnClickListener mySettingsHandler = new View.OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
System.out.println("Running populate method");
for (int i = 0; i < 9; i++) {
if (v.getId() == level[i].getId()) {
String prefKey = String.format("lev%s", i);
if (preferences.getBoolean(prefKey, false) == false) {
System.out.println("Yep");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(prefKey, true);
editor.commit();
level[i].setBackgroundResource(R.mipmap.settings_verbs);
} else {
System.out.println("nope");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(prefKey, false);
editor.commit();
level[i].setBackgroundResource(R.mipmap.ic_launcher);
}
}
}
}
};

}

最佳答案

每次调用 onCreate 时,您都在设置默认值。尝试

if (savedInstanceState == null) {
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
}

关于java - SharedPreferences 编辑保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31002644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com