旋转设备丢失数据

时间:2011-11-24 08:59:25

标签: android

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.login);
   }
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
   }
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
  String phonenumber = phoneNumberLogin.getText().toString();
  savedInstanceState.putString("PhoneNumber", phonenumber);
  super.onSaveInstanceState(savedInstanceState);
 }
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  String  phonenumber= savedInstanceState.getString("PhoneNumber");
  if (phonenumber != null) {
  EditText FirstName = (EditText) findViewById(R.id.editTextname);
  FirstName.setText(phonenumber);
}
  super.onRestoreInstanceState(savedInstanceState);
}

我有一个editText(用于输入电话号码)。在纵向模式下,我输入数字,然后在旋转电话后,输入的数据消失了。我保存数据savedInstanceState但我不知道如何在旋转手机时恢复键入的数据。请帮忙。

2 个答案:

答案 0 :(得分:1)

简单的方法是避免在轮换时重新创建活动。将您的AndroidManifest.xml更改为包含android:configChanges="keyboardHidden|orientation",如下所示:

<activity android:name="MyActivity" android:configChanges="keyboardHidden|orientation"></activity>

您的布局需要支持设备支持的任何方向。还有一些其他事项需要考虑:Why not use always android:configChanges="keyboardHidden|orientation"?

答案 1 :(得分:0)

尝试将onRestoreInstanceState中的电话号码移至onCreate方法 或尝试这样的事情:

@Override
public Object onRetainNonConfigurationInstance()
{        
    return phoneNumberLogin.getText().toString();
}

和onCreate

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.login);
   String  phonenumber= (String)getLastNonConfigurationInstance();
   if (phonenumber != null) {
      EditText FirstName = (EditText) findViewById(R.id.editTextname);
      FirstName.setText(phonenumber);
   }
}