简体   繁体   English

微调器值转换为ListPreference

[英]Spinner value into a ListPreference

I'm trying to save a Spinner value into a ListPreference. 我正在尝试将Spinner值保存到ListPreference中。 I can't get it to work. 我无法正常工作。 I've tried to get this working for a long time now. 我已经尝试了很长时间了。 Does anyone have a solution or can anyone point me in the right direction. 有没有人有解决方案,或者有谁能向我指出正确的方向。

So this is what I have: 这就是我所拥有的:

SharedPreferences preferences;

private static final String KEY_WEIGHT_PREFERENCE = "weightunit";
...

preferences = PreferenceManager.getDefaultSharedPreferences(this);
...

This is the main part, both the Spinner and the ListPreference grab the same data from an array xml. 这是主要部分,Spinner和ListPreference都从数组xml中获取相同的数据。

SharedPreferences.Editor edit = preferences.edit();
    Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
    int selectedPosition = weight.getSelectedItemPosition();
            edit.putInt(KEY_WEIGHT_PREFERENCE, selectedPosition);
            edit.commit();

Thanks! 谢谢!

What isn't working? 什么不起作用?

There's a sample app called Spinner that contains a sample Spinner. 有一个名为Spinner的示例应用程序,其中包含示例Spinner。 It saves the state of the Spinner to saved preferences in onPause(), and restores it in onResume(). 它将微调器的状态保存到onPause()中保存的首选项中,并将其恢复到onResume()中。

I found the answer, the SpinnerValue needs to be saved as a string in order to get recognized by the ListPreference . 我找到了答案, SpinnerValue需要保存为字符串才能被ListPreference识别。

Here's my final code: 这是我的最终代码:

private void updatePreferenceWeightValue() {

    SharedPreferences.Editor edit = preferences.edit();
    Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
    int selectedPosition = weight.getSelectedItemPosition();
    String weightValue = "";
    weightValue = Integer.toString(selectedPosition);
    edit.putString(KEY_WEIGHT_PREFERENCE, weightValue);
    edit.commit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM