[英]Saving Spinner Selection to Sharedpreferences
I'm trying to save a spinner's selection to a shared preference, but I'm having trouble getting it to save. 我正在尝试将微调框的选择保存为共享的首选项,但是我很难保存它。 I have no problem saving text, but the spinner seems to be a bit more difficult.
保存文本没有问题,但微调器似乎有点困难。 I'm using a Preference Connector that I found online that seems to work well for text, so that might be part of the problem.
我使用的是在网上找到的首选项连接器,它似乎可以很好地处理文本,因此这可能是问题的一部分。 Here's a brief section of code that includes only the hair color selector spinner.
这是一段简短的代码,其中仅包括头发颜色选择器微调器。 I think my problem arises when I try to read the SP (readPerson()), but I'm not entirely sure.
我认为当我尝试读取SP(readPerson())时会出现问题,但我不确定。 If you have any suggestions, please let me know.
如果您有任何建议,请让我知道。 Thanks!
谢谢!
public class PreferencesActivity extends Activity {
Spinner hairSpinner; //hair color selector
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_profile);
init();
}
private void init() {
hairSpinner = (Spinner) findViewById(R.id.hair_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.hair_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hairSpinner.setAdapter(adapter);
}
public void save(View view) {
int hairText = hairSpinner.getSelectedItemPosition();
if (hairText != 100)
PreferenceConnector.writeInteger(this, PreferenceConnector.HAIR,
hairText);
}
private void readPerson() {
hairSpinner.setSelection(getText(PreferenceConnector.readInteger(this,
PreferenceConnector.HAIR, 0)));
}
}
This is the part that I found online (a section of it): 这是我在网上找到的部分(其中一部分):
public class PreferenceConnector{
public static final String PREF_NAME = "PEOPLE_PREFERENCES";
public static final int MODE = Context.MODE_PRIVATE;
public static final String HAIR = "HAIR";
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
}
private void readPerson() {
hairSpinner.setSelection(getText(PreferenceConnector.readInteger(this,
PreferenceConnector.HAIR, 0)));
}
Everything looks fine except for the "getText", what is it doing exactly? 除了“ getText”外,其他一切看起来都很好,它到底在做什么? I'm guessing setSelection is looking for an int but getText is converting it to a String or something.
我猜setSelection正在寻找一个int,但getText将其转换为String或其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.