【问题标题】:Spinner Selection - Save to SharedPreferences, then Retrieve微调器选择 - 保存到 SharedPreferences,然后检索
【发布时间】:2011-07-01 09:16:34
【问题描述】:

我在我的应用程序中使用“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);
}

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

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    您必须在所有editor.put(); 语句之后调用一次editor.apply();。否则,您对首选项所做的所有更改都将被丢弃。假设您的数组中的项目根本不会改变位置,那么您可以将所选位置作为 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(); 方法,您必须手动搜索数组才能找到正确的值。

    【讨论】:

    • 我觉得应该是 spinner.setSelection(position) (spinner.setSelected 需要布尔值
    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多