gpt4 book ai didi

java - Spinner 不会在 Android 中保存其状态

转载 作者:行者123 更新时间:2023-12-01 12:38:58 25 4
gpt4 key购买 nike

我找不到使用 SharedPreferences` 保存微调器状态的方法。我使用的代码是这个:

mIo = (Spinner) view.findViewById(R.id.schedulerSpinner);
mIo.setSelection(preferences.getInt("spinnerSelection",0));
String[] availableIo = {"one", "two", "three", "four"};
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),android.R.layout.simple_spinner_item, availableIo);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mIo.setAdapter(adapter);
mIo.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = mIo.getSelectedItemPosition();

String selected = mIo.getItemAtPosition(position).toString();
Toast.makeText(this, "Selected item: " + selected, Toast.LENGHT_SHORT).show();
editor = preferences.edit();
editor.putInt("spinnerSelection", item);
editor.commit();

}
public void onNothingSelected(AdapterView<?> arg0) {

}
});

当我单击该项目时,我希望它顺利进行,并且 toast 可以正确显示该项目,但是如果我关闭并重新打开应用程序,微调器会显示第一个项目,而不是我之前选择的项目。我尝试了不同的方法,但是没有结果。谢谢

最佳答案

它更新到第一个位置的原因是因为您在将适配器设置为微调器之前设置该项目,当时微调器中没有值因此,您调用 setSelection() 没有什么区别,因为新值是由适配器在微调器中设置的。更新您的代码,如下所示

mIo = (Spinner) view.findViewById(R.id.schedulerSpinner);
String[] availableIo = {"one", "two", "three", "four"};
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),android.R.layout.simple_spinner_item, availableIo);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mIo.setAdapter(adapter);
//SET SELECTION AFTER YOU SET THE ADAPTER NOT BEFORE IT
mIo.setSelection(preferences.getInt("spinnerSelection",0));
mIo.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = mIo.getSelectedItemPosition();

String selected = mIo.getItemAtPosition(position).toString();
Toast.makeText(this, "Selected item: " + selected, Toast.LENGHT_SHORT).show();
editor = preferences.edit();
editor.putInt("spinnerSelection", item);
editor.commit();

}
public void onNothingSelected(AdapterView<?> arg0) {

}
});

关于java - Spinner 不会在 Android 中保存其状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25302398/

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