如何设置文本并将其保存在EditText中

时间:2017-05-14 22:20:00

标签: android

我有两个EditText字段(假设它们是空的)我会在那里写文本,它会在那里被记住,因为当我走出窗口然后返回时会在那里输入文字。谢谢你的帮助:))

Button button1;
Button button2;
TextView devices;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.change_url);
    button1 = (Button) findViewById(R.id.button9);
    button2 = (Button) findViewById(R.id.button10);


    button2.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            TextView buildings = (TextView) findViewById(R.id.buildings);
            String a = buildings.getText().toString();
            buildings.setText(a);
        }
    });

}

2 个答案:

答案 0 :(得分:0)

就我的观点而言, 将您的值存储在共享首选项中,并且只要您希望此值从共享首选项获取并放入编辑文本。

答案 1 :(得分:0)

当您退出活动并希望在回来时恢复数据时,您应该覆盖onSaveInstanceState(Bundle savedInstanceState)。在此方法中,当您再次回到Bundle中时,需要保存要恢复的所有数据。

以您的案例为例:

首先:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is killed and restarted.
  savedInstanceState.putString("EditText1", mEditText1.getText().toString());
  savedInstanceState.putString("EditText2", mEditText2.getText().toString());
}

然后,要恢复它,您需要覆盖onRestoreInstanceState(Bundle savedInstanceState)

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  String text1 = savedInstanceState.getString("EditText1");
  String text2 = savedInstanceState.getString("EditText2");
  //At this point you recovered your data, so you can put in the EditText
  mEditText1.setText(text1);
  mEditText2.setText(text2);
}

更多参考资料:https://developer.android.com/guide/components/activities/activity-lifecycle.html