旋转设备时EditText数据丢失

Yog*_*ani 2 android orientation onconfigurationchanged android-edittext

伙计们,我完成了它.我一直在谷歌搜索过去2天,但我找不到确切的解决方案.每个人都在谈论configChanges和所有那些在我的案例中似乎不起作用的陈词滥调.

我有一个登录屏幕,由2个EditTexts组成.现在,此登录屏幕具有不同的纵向和横向布局.所以我不得不在layout文件夹中创建一个login.xml,在layout-land文件夹中创建另一个login.xml.为了支持方向更改,我在LoginActivity类中覆盖了onConfigurationChanged()方法.在这个方法中,我调用setContentView(R.layout.login)方法,以便将适当的login.xml设置为每个方向的布局.

毕竟我在我的清单文件中定义了以下内容:

android:configChanges="orientation|keyboardHidden"
Run Code Online (Sandbox Code Playgroud)

但我仍然面临着着名的老问题.如果Edittext中有任何文本并且设备已旋转,则该文本将丢失.我不想丢失那个文字.有可能吗?我已经读过我们可以使用onSaveInstanceState(Bundle savedInstanceState)方法来做到这一点,我甚至尝试了它,但它对我不起作用.请帮忙.提前致谢.

Ily*_*dov 5

使用put方法在onSaveInstanceState中存储值:

protected void onSaveInstanceState(Bundle extra) {
  super.onSaveInstanceState(extra);
  extra.putString("text", "your text here");
}
Run Code Online (Sandbox Code Playgroud)

并恢复onCreate中的值:

public void onCreate(Bundle extra) {
  if (extra != null) {
    String value = extra.getString("text");
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑(实际工作的):

尝试从清单中删除android:configChanges ="orientation | keyboardHidden".

祝好运!

  • 在清单中设置configChanges = orientation可防止在方向更改时重新创建应用程序。 (2认同)