将来自EditText的数字输入保存到SharedPreferences中 [英] Save number input from EditText into SharedPreferences
本文介绍了将来自EditText的数字输入保存到SharedPreferences中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在寻找解决此问题的方法,但似乎没有任何效果.我想将输入从EditText保存到SharedPreferences,当我返回页面时,我希望该输入保持在那里直到清除.
I have searched for solutions to this problem but none seem to work. I want to save an input from EditText to SharedPreferences and when I return to the page I would like that input to remain there until cleared.
我已经尝试过这样做,但无法正常工作,我不确定为什么
I have tried to do it like this but it won't work and I am unsure why
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
loadStepPref();
final Button saveStepLength = (Button) findViewById(R.id.saveStepButton);
if(saveStepLength != null) {
saveStepLength.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.editStepLength);
saveStepLength.setVisibility(View.GONE);
//Hide keypad
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
saveStepPref("editStepLength", null);
}
});
}
private void loadStepPref() {
EditText inputStepLength = (EditText) findViewById(R.id.editStepLength);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String value = sp.getString("editStepLength", null);
inputStepLength.setText(value);
}
private void saveStepPref(String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putString(key, value);
edit.apply();
}
}
这是xml的部分:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/step_length_data"
android:id="@+id/textView12"
android:layout_gravity="center_horizontal"
android:layout_marginTop="41dp"
android:layout_alignParentTop="true"
android:layout_toStartOf="@+id/returnHomeButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/textView12"
android:inputType="number"
android:layout_alignBottom="@id/textView12"
android:id="@+id/editStepLength"
android:hint = "@string/step_length_entry"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save"
android:id="@+id/saveStepButton"
android:layout_alignTop="@+id/editStepLength"
android:layout_toEndOf="@+id/editStepLength" />
推荐答案
您永远都无法使用它,因为您总是保存null!
You never get it work .. because you are saving null always !
saveStepPref("editStepLength", null);
将其更改为
saveStepPref("editStepLength", edittext.getText().toString());
这篇关于将来自EditText的数字输入保存到SharedPreferences中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文