【发布时间】:2016-11-15 08:25:16
【问题描述】:
我已经搜索过这个问题的解决方案,但似乎都没有。我想将 EditText 中的输入保存到 SharedPreferences 中,当我返回页面时,我希望该输入保留在那里直到被清除。
我尝试过这样做,但它不起作用,我不确定为什么
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" />
【问题讨论】:
标签: android android-edittext sharedpreferences