4

我在我的应用程序中使用“SharedPreferences”来保留从多个编辑文本框中保存/检索字符串值的能力,这工作得很好。我的活动中还有一个 Spinner,它带有一个字符串数组,它的可用值。但我不清楚如何将微调器选择写入 SharedPreferences,然后再阅读 SharedPreferences 以退休并设置它的值。

这是我对edittext的配置:

-激活将值保存到 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();
}

-激活从 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);
}

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

4

1 回答 1

7

你必须在你所有的陈述editor.apply();之后打电话一次。editor.put();否则,您对首选项所做的所有更改都将被丢弃。假设您的数组中的项目根本不会改变位置,那么您可以将所选位置作为 int 存储在您的首选项中。

保存:

int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();

装载:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));

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

String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.apply();

通过遍历数组并检查 array[i] 与存储在 prefs 中的值来查找字符串的位置。然后调用yourSpinner.setSelected(position)。如果您使用 ArrayList 而不是这部分可以通过调用在没有循环的情况下完成

ArrayList.indexOf(prefs.getString("spinnerSelection", ""));

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

于 2011-02-21T16:02:06.270 回答