保存并检索选定的微调器位置

时间:2012-11-17 14:46:14

标签: android android-widget spinner sharedpreferences

如何保存和检索微调器选择,所以当你回来时,选择了微调器上的相同项目?也许有共享偏好?

1 个答案:

答案 0 :(得分:6)

将数据保存在sharedPreferences上(将此代码放在onItemSelected()方法上并保存所选值的spinner位置):

int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();

sharedPreferences获取数据:

SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
  // set the selected value of the spinner 
  spinner.setSelection(spinnerValue);
}

请参阅:set selection in spinner 而这:get the position of the selected item in a spinner

另见: