[英]Saving and loading spinner value using sharedPreferences
我嘗試使用sharedPreferences
在spinner
保存和加載所選項目。 即使代碼沒有顯示錯誤,也無法正常工作。 有人幫忙。
country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.countries_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
public void saveFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPref.edit();
int userChoice = country.getSelectedItemPosition();
editor.putInt("userChoiceSpinner",userChoice);
}
public void readFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",0);
country.setSelection(spinnerValue);
}
您忘記了使用editor.apply();
在SharedPreferences
保存價值
SharedPreferences
對象。 這將自動執行請求的修改,從而替換SharedPreferences
當前存在的任何內容。 嘗試這個
public void saveFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPref.edit();
int userChoice = country.getSelectedItemPosition();
editor.putInt("userChoiceSpinner",userChoice);
editor.apply();
}
您將國家/地區和微調器設置為相同的ID,可能顯示一個微調器未設置數據
country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.