0

我有一个名为 的微调器视图Spinner_Gender,我制作了数组、数组适配器并制作了onItemSelectedListener. 我想将选定的项目位置保存为共享首选项的整数,我尝试使用带有 Editor 和 putInt 的字符串,它保存得很好。但是当使用它将保存的数据重新加载到微调器.setSelection时会出错,因为它需要一个整数而不是字符串。同样,在 sharedpreference 中尝试 Integer 时,我无法将所选项目位置保存到其中,因为 putInt 只需要一个字符串即可放入 int 。

对不起,很长的问题,但我搜索了很多,找不到答案。请再问两个问题: spinner 的整数名称是selectedItemPosition什么?我怎样才能将它存储到sharedpreference

代码:

final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter); 
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { 
      public void onItemSelected(AdapterView<?> parent, View itemSelected, 
                                final int selectedItemPosition, long selectedId) 
      { 
          int selectedPosition = spinner.getSelectedItemPosition(); 
          Editor editor = mGameSettings.edit(); 
          editor.putInt(myNum,selectedPosition); 
          editor.commit(); 
      }
}
4

3 回答 3

1

I don't quite understand what's your issue with SharedPreferences. When you want to save the value you do something like this :

SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
Editor editTest = test.edit();
editTest.putInt("key", id_from_spinner);
editTest.commit();

When you want to get the value you do something like this :

SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
int id = test.getInt("key", -1);
if(id != -1) {
    //use it in your spinner
} else {
    //abort because value was not set
}
于 2012-07-19T21:41:11.333 回答
0

要将 int 转换为可以使用Integer.toString(theInteger)的 String 并将 String 转换为可以使用的 int Integer.parseInt(theString)

于 2012-07-19T17:32:47.940 回答
0

你应该做这样的事情

spinner.setSelection(dataAdapter.getPosition(genderstring));

更新 :

final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter); 

spinner.setSelection(mGameSettings.getInt("gender", 0));

spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { 
      public void onItemSelected(AdapterView<?> parent, View itemSelected, 
                                final int selectedItemPosition, long selectedId) 
      { 
          Editor editor = mGameSettings.edit(); 
          editor.putInt("gender", selectedItemPosition); 
          editor.commit(); 
      }
}
于 2012-07-19T17:35:07.027 回答