【发布时间】:2018-01-14 14:34:07
【问题描述】:
我正在编写一个简单的游戏来学习编程。最后,我希望最终按钮根据“分数”转到不同的结尾,“分数”是保存在 sharedpref 中的整数变量。
我的方法是设置一个“if/else if”循环,该循环编辑一个名为“page”的字符串共享首选项,然后将“page”应用于按钮操作。很明显,我的 if/else if 循环没有编辑“页面”sharedpref,因为按钮一直使用先前的值。
这是我对代码的尝试;感谢您的帮助!
public Button button;
public void init() {
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ScorePref", MODE_PRIVATE);
int score = pref.getInt("Score", 0);
//these two lines recall the "score" integer
SharedPreferences saveGame = getSharedPreferences("PrefFile", Context.MODE_PRIVATE);
String page = saveGame.getString
("page", "com.twigofknowledge.variablebuttonpractice.MainActivity");
//and then the two above here recall the "page" string sharedpref
SharedPreferences.Editor editor = saveGame.edit();
//this is the editor that will change the sharedpref
@Override
public void onClick(View v) {
if (score >= 150) {
editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page6");
editor.apply();
} else if (score <= 150) {
SharedPreferences.Editor editor = saveGame.edit();
editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page5");
editor.apply();
}
Intent gotopage = new Intent();
gotopage.setClassName("com.twigofknowledge.variablebuttonpractice", page);
startActivity(gotopage);
}
});
}
【问题讨论】:
标签: android button sharedpreferences