【发布时间】:2018-11-18 17:08:08
【问题描述】:
我有一个奇怪的错误,我不确定它为什么会发生,
我有 2 个活动:活动 A 和活动 B。
当应用启动时,它会初始化一次微调器。我去第二个活动然后回去
Activity A 的onRestart() 将被调用。我的问题是,即使我清除我的微调器并在 onRestart() 中重新初始化它,它仍然会读取值。
例如,如果当您转到活动 B 然后返回活动 A 时,微调器有 1/2,则微调器有 = 1/2/1/2。
我觉得这很奇怪,因为当我将微调器适配器设置为 null 并在我从活动 B 返回活动 A 时注释掉微调器的初始化时,我的微调器是空的。
这是我的代码:
@Override public void onRestart() {
super.onRestart();
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
initSpinner();// if this is commented out spinner is cleared, if not commented the same valus are added again
}
这是 initSpinner 的代码(从共享首选项读取)这不是问题
public void initSpinner(){
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
SharedPreferences prefs = this.getSharedPreferences("Locations", Context.MODE_PRIVATE); //preffilename
SharedPreferences.Editor editor = prefs.edit();
editor.putString("1","St. Catharines");
editor.putString("2","Toronto");
editor.putString("3","Niagara Falls");
editor.commit();
int s = prefs.getAll().size();
for(int f=0;f<25;f++) {
if (prefs.getString(String.valueOf(f + 1), null) != null) {
DefaultLocations.add(prefs.getString(String.valueOf(f + 1), null));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, DefaultLocations);
//set the spinners adapter to the previously created one.
location.setAdapter(adapter);
}
【问题讨论】:
-
在调用 init 之前手动清除微调器