简体   繁体   中英

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. When field length = 0, I set error

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) . Before the switch in orientation the onSaveInstanceState(Bundle outState) method will be called if it is overridden in your Activity.

You can save the state of your errors in the Bundle passed into the onSaveInstanceState method. This bundle is passed to your onCreate() method as the savedInstanceState Bundle.

Therefore you need to override the onSaveInstanceState method in your Activity as follows (saving the state of your errors):

@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. 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. So all your state is lost.

Use SharedPreferences to store and restore your state and TextEdit values.

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.

You should take a look at the developer docs on how to Handle Runtime Changes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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