Spinner没有在Android中保存它的状态

时间:2014-08-14 07:31:07

标签: java android sharedpreferences android-spinner

我无法使用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) {

     }
});

当我点击我希望它顺利的项目并且吐司正确显示项目,但如果我关闭并重新打开应用程序,微调器显示第一个项目,而不是我之前选择的..我尝试了不同的方式,但没有结果。感谢

1 个答案:

答案 0 :(得分:1)

它更新到第一个位置的原因是因为你在将适配器设置为微调器之前设置了项目,那时微调器中没有值 因此,调用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) {

     }
});