简体   繁体   English

Android:在更改方向时保存错误状态

[英]android: save error state on change orientation

I make a login form with dynamic field validation. 我用动态字段验证制作了一个登录表单。 I have 3 fields username, email & password & all of these field are required. 我有3个字段用户名,电子邮件和密码,所有这些字段都是必填字段。 When field length = 0, I set error 当字段长度= 0时,我设置错误

editText.setError( getText(R.string.cannot_be_blank) );

and this code works fine, but when I change the orientation, all the errors disappear How to save error state? 并且此代码可以正常工作,但是当我更改方向时,所有错误都消失了如何保存错误状态?

Thanks. 谢谢。

When the orientation is changed the framework will recreate the Activity by calling onCreate(Bundle savedInstanceState) . 更改方向后,框架将通过调用onCreate(Bundle savedInstanceState)来重新创建Activity。 Before the switch in orientation the onSaveInstanceState(Bundle outState) method will be called if it is overridden in your Activity. 在方向切换之前,如果在您的Activity中重写了onSaveInstanceState(Bundle outState)方法,则该方法将被调用。

You can save the state of your errors in the Bundle passed into the onSaveInstanceState method. 您可以在传递给onSaveInstanceState方法的Bundle中保存错误状态。 This bundle is passed to your onCreate() method as the savedInstanceState Bundle. 此捆绑包作为savedInstanceState捆绑包传递到onCreate()方法。

Therefore you need to override the onSaveInstanceState method in your Activity as follows (saving the state of your errors): 因此,您需要按如下所示重写Activity中的onSaveInstanceState方法(保存错误状态):

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("errorOccurred", errorState);
    super.onSaveInstanceState(outState);
}

Then in your onCreate method check if the savedInstateState Bundle is null or not. 然后在您的onCreate方法中检查savedInstateState Bundle是否为null。 If not, you can retrieve the values out of it with the following code: 如果没有,您可以使用以下代码从中检索值:

boolean errorOccurred = false;  
if (savedInstanceState != null) {
    errorOccurred = savedInstanceState.getBoolean("errorOccurred"); 
}

When the orientation is changed the Android framework destroys the Activity and then creates a new one for the new orientation. 更改方向后,Android框架会销毁Activity,然后为新方向创建一个新的活动。 So all your state is lost. 因此,您的所有状态都丢失了。

Use SharedPreferences to store and restore your state and TextEdit values. 使用SharedPreferences可以存储和还原状态和TextEdit值。

What happens when you turn the device is that your Activity runs through its lifecycle in order to deal with the fact that the layout must change from portrait to landscape. 转动设备时会发生以下情况:“ Activity贯穿其生命周期,以应对布局必须从纵向更改为横向的事实。

You should take a look at the developer docs on how to Handle Runtime Changes . 您应该查看有关如何处理运行时更改的开发人员文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM