Android retain callback state after configuration change

眉间皱痕 提交于 2019-11-29 07:15:23

Here is why you see this behavior:

  1. When 'onCreate' method is called first time, it has no saved state. Which means Bundle savedInstanceState parameter is null.
  2. When configuration changed, Android paths non-null value in savedInstanceState parameter.
  3. After configuration is changed, and onCreate returns, Android calls onRestoreInstateState.
  4. By default, all views that have id are trying to restore their state, EditText restores its state too (actually, that TextView who restores most of it).
  5. At some place during state restoration (but after onCreate method is completed) your EditText control calls setText on himself in order to restore text that it had just before configuration changed.
  6. Your new TextWatcher that you added in onCreate method is notified about this change.

Just to make this clear, your old TextWatcher, that you added on first call to onCreate, is not preserved! Its new TextWatcher, that was added on last call to onCreate, which receives the text change notification.

You can examine TextView.onRestoreInstanceState yourself.

Kakey

When ever you rotate the device the onCreate method of activity called again.if you want to prevent to call onCreate when rotating the device do the following code in the Manifest

android:configChanges="orientation|keyboardHidden"

and in your activity

public void onConfigurationChanged(Configuration newConfig)
{       
    super.onConfigurationChanged(newConfig);    

    if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
    {

    }      
    else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
    {

    }  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!