Preventing WebView reload on Rotate - Android Studio

后端 未结 3 1966
执笔经年
执笔经年 2020-12-09 22:53

When I rotate my screen, the WebView reloads the whole page. So I disabled rotation in Android_Manifest.xml file, but it would be really cool if I could make rotation possib

相关标签:
3条回答
  • 2020-12-09 23:34

    There are 3 points must be done. This is a full solution for me.

    1. AndroidManifest.xml need config both orientation and screenSize in android:configChanges for target activity

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.skatetube.skatetube">
          <application
              <activity android:name=".WebViewActivity"
                  android:configChanges="orientation|screenSize">
              </activity>
          </application>
      </manifest>
      
    2. Need to override onSaveInstanceState and onRestoreInstanceState of Activity to make state can be restore when rotated

      @Override
      protected void onSaveInstanceState(Bundle outState)
      {
          super.onSaveInstanceState(outState);
          mWebView.saveState(outState);
      }
      
      @Override
      protected void onRestoreInstanceState(Bundle savedInstanceState)
      {
          super.onRestoreInstanceState(savedInstanceState);
          mWebView.restoreState(savedInstanceState);
      }
      
    3. Not loading URL again when screen rotate, use savedInstanceState to know current status in onCreate() of target activity

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
          mWebView = (WebView) findViewById(R.id.webView_h5);
          if (savedInstanceState == null) {
              mWebView.loadUrl(url);
          }
      }
      

    Miss any one of those three, my activity still reload.

    0 讨论(0)
  • 2020-12-09 23:41

    well no need of java code just copy this code in place of your activity tag in Manifest.xml

    <activity
            android:name=".SkateTube"
            android:theme="@style/AppTheme.NoActionBar"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:label="State preserving implementation"/>
    
    0 讨论(0)
  • 2020-12-09 23:46

    All you need to do is Override onSaveInstanceState and onRestoreInstanceState.

    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
    

    and one other solution could be to update your Activity tag in manifest to

    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
    
    0 讨论(0)
提交回复
热议问题