需要保存 EditText 框的状态。请帮忙!
我有一个 EditText 的代码,但我不知道如何为位于同一页面上的第二个 editText 框制作相同的代码。这是我的代码:
package tryone.now.forfreenow;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class notepad extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editBox =(EditText)findViewById(R.id.editText1);
}
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
editBox.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
editBox.setSelection(selectionStart, selectionEnd);
}
}
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("text", editBox.getText().toString());
editor.putInt("selection-start", editBox.getSelectionStart());
editor.putInt("selection-end", editBox.getSelectionEnd());
editor.commit();
}
private EditText editBox;
}
I have code for one EditText, but I can not figure out how to make same code for second editText Box, that is located on the same page. Here is my code:
package tryone.now.forfreenow;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class notepad extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editBox =(EditText)findViewById(R.id.editText1);
}
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
editBox.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
editBox.setSelection(selectionStart, selectionEnd);
}
}
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("text", editBox.getText().toString());
editor.putInt("selection-start", editBox.getSelectionStart());
editor.putInt("selection-end", editBox.getSelectionEnd());
editor.commit();
}
private EditText editBox;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我正在回答我自己的问题。它可以 100% 保存两个 editText 框的状态。
I am answering my own question.It works 100% to save state on two editText boxes.