微调器选择 - 保存到SharedPreferences,然后检索

Dev*_*vin 3 android sharedpreferences

我在我的应用程序中使用"SharedPreferences"来保留从多个edittext框保存/检索字符串值的功能,这样就可以了.我的活动中还有一个Spinner,它有一个字符串数组,用于它的可用值.但我不清楚如何将微调器选择写入SharedPreferences,然后读取SharedPreferences以退出并设置它的值.

这是我对edittext的配置:

-Button激活保存值到SharedPreferences-

public void buttonSaveSendClick(View view) {

    SharedPreferences.Editor editor = getPreferences(0).edit();

    EditText editTextCallId = (EditText) findViewById(R.id.editTextCallId);
    editor.putString("editTextCallIdtext", editTextCallId.getText().toString());
    editor.putInt("selection-startCallId", editTextCallId.getSelectionStart());
    editor.putInt("selection-endCallId", editTextCallId.getSelectionEnd());
    editor.commit();
}
Run Code Online (Sandbox Code Playgroud)

-Button激活从SharedPreferences恢复上次保存的值 -

public void buttonRestoreLastClick(View view) {

    SharedPreferences prefs = getPreferences(0); 

    EditText editTextCallId = (EditText) findViewById(R.id.editTextCallId);
    String editTextCallIdtextrestored = prefs.getString("editTextCallIdtext", null);
    editTextCallId.setText(editTextCallIdtextrestored, EditText.BufferType.EDITABLE);
    int selectionStartCallId = prefs.getInt("selection-startCallId", -1);
    int selectionEndCallId = prefs.getInt("selection-endCallId", -1);
    editTextCallId.setSelection(selectionStartCallId, selectionEndCallId);
}
Run Code Online (Sandbox Code Playgroud)

有关如何在第一个按钮(保存)中构建微调器选定值的集合的任何建议?那么如何在按下"恢复"按钮时将保存的值返回到微调器视图?

Foa*_*Guy 6

您必须在所有editor.put()语句之后调用editor.commit()一次.否则,您对首选项所做的所有更改都将被丢弃.假设数组中的项目根本不会改变位置,那么您可以将所选位置作为int存储在首选项中.

保存:

int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();
Run Code Online (Sandbox Code Playgroud)

载入:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
Run Code Online (Sandbox Code Playgroud)

如果数组中的项目将要更改,那么您将必须存储实际的字符串,而不是位置.像这样的东西会起作用:

String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.apply();
Run Code Online (Sandbox Code Playgroud)

通过循环遍历数组并根据存储在prefs中的值检查array [i]来查找字符串的位置.然后调用spinner.setSelected(position).如果使用ArrayList,则可以通过调用在没有循环的情况下完成此部分

editor.apply();

请注意,只有ArrayList具有indexOf方法.在普通数组上,您不能使用indexOf()方法,您必须手动搜索数组以找到正确的值.