问题是轮换后的性能。WebView必须重新加载页面,这可能有点乏味。
在不每次都从源中重新加载页面的情况下,处理方向更改的最佳方法是什么?
问题是轮换后的性能。WebView必须重新加载页面,这可能有点乏味。
在不每次都从源中重新加载页面的情况下,处理方向更改的最佳方法是什么?
Answers:
如果您不希望WebView在方向更改时重新加载,只需在Activity类中重写onConfigurationChanged:
@Override
public void onConfigurationChanged(Configuration newConfig){        
    super.onConfigurationChanged(newConfig);
}并在清单中设置android:configChanges属性:
<activity android:name="..."
          android:label="@string/appName"
          android:configChanges="orientation|screenSize"有关更多信息,请参见:http : 
//developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
https://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges
configChanges属性将添加到子类Activity 2)如果您的应用程序依赖于多个项目,则该configChanges属性将被添加到该项目的清单中。依赖关系树的顶部(可能不是包含Activity类的项目)。
                    onConfigurationChanged方法重写是没有用的。
                    编辑:此方法不再按文档中所述工作
原始答案:
这可以通过覆盖onSaveInstanceState(Bundle outState)您的活动并saveState从Web视图中调用来解决:
   protected void onSaveInstanceState(Bundle outState) {
      webView.saveState(outState);
   }当然,在重新放大Webview之后,请在onCreate中恢复它:
public void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.blah);
   if (savedInstanceState != null)
      ((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}最好的答案是遵循此处找到的Android文档, 基本上这将阻止Webview重新加载:
<activity android:name=".MyActivity"
      android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection|uiMode"
      android:label="@string/app_name">(可选)您可以通过覆盖onConfigurationChanged活动来修复异常(如果有):
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}我试过使用onRetainNonConfigurationInstance(返回WebView),然后在onCreate期间使用getLastNonConfigurationInstance将其恢复并重新分配它。
似乎还没有工作。我禁不住觉得自己真的很亲密!到目前为止,我只得到了一个空白/白色背景的WebView。张贴在这里,希望有人可以帮助将其推向终点。
也许我不应该通过WebView。也许来自WebView中的对象?
我尝试的另一种方法(不是我的最爱)是在活动中设置此方法:
 android:configChanges="keyboardHidden|orientation"...然后在这里几乎什么也不做:
@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  // We do nothing here. We're only handling this to keep orientation
  // or keyboard hiding from causing the WebView activity to restart.
}可行,但可能不被视为最佳做法。
同时,我还有一个ImageView,我想根据旋转自动更新。事实证明这很容易。在我的res文件夹,我必须drawable-land和drawable-port持有横向/纵向变化,然后我用R.drawable.myimagename了ImageView的的来源和Android‘做正确的事’ -耶!
...除非您注意配置更改,否则不会。:(
所以我很矛盾。使用onRetainNonConfigurationInstance和ImageView旋转可以工作,但是WebView持久性不会...或使用onConfigurationChanged且WebView保持稳定,但ImageView不会更新。该怎么办?
最后一点:就我而言,强制定向不是可以接受的折衷方案。我们确实确实想很好地支持轮换。有点喜欢Android浏览器应用程序的功能!;)
一种折衷办法是避免轮换。添加此选项可仅将活动固定为纵向。
android:screenOrientation="portrait"处理方向更改和防止在Rotate上重新加载WebView的最佳方法。
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}考虑到这一点,为防止每次更改方向都调用onCreate(),您必须添加 android:configChanges="orientation|screenSize" to the AndroidManifest.
要不就 ..
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"`我感谢这有点晚,但这是我在开发解决方案时使用的答案:
AndroidManifest.xml
    <activity
        android:name=".WebClient"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize" <--- "screenSize" important
        android:label="@string/title_activity_web_client" >
    </activity>WebClient.java
public class WebClient extends Activity {
    protected FrameLayout webViewPlaceholder;
    protected WebView webView;
    private String WEBCLIENT_URL;
    private String WEBCLIENT_TITLE;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_client);
        initUI();
    }
    @SuppressLint("SetJavaScriptEnabled")
    protected void initUI(){
        // Retrieve UI elements
        webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));
        // Initialize the WebView if necessary
        if (webView == null)
        {
            // Create the webview
            webView = new WebView(this);
            webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
            webView.getSettings().setSupportZoom(true);
            webView.getSettings().setBuiltInZoomControls(true);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            webView.setScrollbarFadingEnabled(true);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setPluginState(android.webkit.WebSettings.PluginState.ON);
            webView.getSettings().setLoadsImagesAutomatically(true);
            // Load the URLs inside the WebView, not in the external web browser
            webView.setWebViewClient(new SetWebClient());
            webView.setWebChromeClient(new WebChromeClient());
            // Load a page
            webView.loadUrl(WEBCLIENT_URL);
        }
        // Attach the WebView to its placeholder
        webViewPlaceholder.addView(webView);
    }
    private class SetWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.web_client, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }else if(id == android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            return;
        }
        // Otherwise defer to system default behavior.
        super.onBackPressed();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig){
        if (webView != null){
            // Remove the WebView from the old placeholder
            webViewPlaceholder.removeView(webView);
        }
        super.onConfigurationChanged(newConfig);
        // Load the layout resource for the new configuration
        setContentView(R.layout.activity_web_client);
        // Reinitialize the UI
        initUI();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        // Save the state of the WebView
        webView.saveState(outState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // Restore the state of the WebView
        webView.restoreState(savedInstanceState);
    }
}到了2015年,许多人正在寻找仍可在Jellybean,KK和Lollipop手机上使用的解决方案。经过很多努力后,我找到了一种更改方向后保持Web视图完整的方法。我的策略基本上是将webview存储在另一个类的单独的静态变量中。然后,如果发生旋转,我将从活动中分离Web视图,等待定向完成,然后将Web视图重新附加到活动中。例如...首先将其放在清单中(keyboardHidden和keyboard是可选的):
<application
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name="com.myapp.abc.app">
    <activity
            android:name=".myRotatingActivity"
            android:configChanges="keyboard|keyboardHidden|orientation">
    </activity>在单独的应用程序类中,输入:
     public class app extends Application {
            public static WebView webview;
            public static FrameLayout webviewPlaceholder;//will hold the webview
         @Override
               public void onCreate() {
                   super.onCreate();
    //dont forget to put this on the manifest in order for this onCreate method to fire when the app starts: android:name="com.myapp.abc.app"
                   setFirstLaunch("true");
           }
       public static String isFirstLaunch(Context appContext, String s) {
           try {
          SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
          return prefs.getString("booting", "false");
          }catch (Exception e) {
             return "false";
          }
        }
    public static void setFirstLaunch(Context aContext,String s) {
       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(aContext);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("booting", s);
            editor.commit();
           }
        }在活动中输入:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(app.isFirstLaunch.equals("true"))) {
            app.setFirstLaunch("false");
            app.webview = new WebView(thisActivity);
            initWebUI("www.mypage.url");
        }
}
@Override
    public  void onRestoreInstanceState(Bundle savedInstanceState) {
        restoreWebview();
    }
public void restoreWebview(){
        app.webviewPlaceholder = (FrameLayout)thisActivity.findViewById(R.id.webviewplaceholder);
        if(app.webviewPlaceholder.getParent()!=null&&((ViewGroup)app.webview.getParent())!=null) {
            ((ViewGroup) app.webview.getParent()).removeView(app.webview);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
        app.webview.setLayoutParams(params);
        app.webviewPlaceholder.addView(app.webview);
        app.needToRestoreWebview=false;
    }
protected static void initWebUI(String url){
        if(app.webviewPlaceholder==null);
          app.webviewPlaceholder = (FrameLayout)thisActivity.findViewById(R.id.webviewplaceholder);
        app.webview.getSettings().setJavaScriptEnabled(true);       app.webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        app.webview.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        app.webview.getSettings().setSupportZoom(false);
        app.webview.getSettings().setBuiltInZoomControls(true);
        app.webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        app.webview.setScrollbarFadingEnabled(true);
        app.webview.getSettings().setLoadsImagesAutomatically(true);
        app.webview.loadUrl(url);
        app.webview.setWebViewClient(new WebViewClient());
        if((app.webview.getParent()!=null)){//&&(app.getBooting(thisActivity).equals("true"))) {
            ((ViewGroup) app.webview.getParent()).removeView(app.webview);
        }
        app.webviewPlaceholder.addView(app.webview);
    }最后,简单的XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".myRotatingActivity">
    <FrameLayout
        android:id="@+id/webviewplaceholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>解决方案中有几处可以改进的地方,但是我已经花了很多时间,例如:一种较短的方法来验证Activity是否是首次启动,而不是使用SharedPreferences存储。此方法可保留完整的Webview(afaik),其文本框,标签,UI,javascript变量和URL未反映的导航状态。
更新:当前的策略是将WebView实例分离时将其移至Application类,而不是保留的片段,并像Josh一样将其重新附加到简历上。为了防止应用程序关闭,如果要在用户在应用程序之间切换时保持状态,则应使用前台服务。
如果使用片段,则可以使用WebView的保留实例。Web视图将保留为类的实例成员。但是,您应该在OnCreateView中附加Web视图,并在OnDestroyView之前分离Web视图,以防止其被父容器破坏。
class MyFragment extends Fragment{  
    public MyFragment(){  setRetainInstance(true); }
    private WebView webView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View v = ....
       LinearLayout ll = (LinearLayout)v.findViewById(...);
       if (webView == null) {
            webView = new WebView(getActivity().getApplicationContext()); 
       }
       ll.removeAllViews();
       ll.addView(webView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
       return v;
    }
    @Override
    public void onDestroyView() {
        if (getRetainInstance() && webView.getParent() instanceof ViewGroup) {
           ((ViewGroup) webView.getParent()).removeView(webView);
        }
        super.onDestroyView();
    } 
}PS点数转到kcoppock答案
至于'SaveState()',它根据官方文档不再起作用:
请注意,此方法不再存储此WebView的显示数据。如果从未调用restoreState(Bundle),则以前的行为可能会泄漏文件。
setRetainInstance确实保留了Fragment,但视图(以及WebView)仍然被销毁。
                    @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);    
}
@Override
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);    
}这些方法可以在任何活动上覆盖,基本上,它基本上允许您在每次创建/销毁活动时保存和恢复值,当屏幕方向更改时,该活动在后台被破坏并重新创建,因此您可以使用这些方法更改期间临时存储/恢复状态。
您应该更深入地研究以下两种方法,并查看它是否适合您的解决方案。
http://developer.android.com/reference/android/app/Activity.html
我发现最好的解决方案是使用MutableContextWrapper,而不泄漏先前的Activity参考,也无需设置configChanges..。
我在这里实现了这一点:https : //github.com/slightfoot/android-web-wrapper/blob/48cb3c48c457d889fc16b4e3eba1c9e925f42cfb/WebWrapper/src/com/example/webwrapper/BrowserActivity.java
这是唯一对我有用的东西(我什至在其中使用了save实例状态,onCreateView但它并不那么可靠)。
public class WebViewFragment extends Fragment
{
    private enum WebViewStateHolder
    {
        INSTANCE;
        private Bundle bundle;
        public void saveWebViewState(WebView webView)
        {
            bundle = new Bundle();
            webView.saveState(bundle);
        }
        public Bundle getBundle()
        {
            return bundle;
        }
    }
    @Override
    public void onPause()
    {
        WebViewStateHolder.INSTANCE.saveWebViewState(myWebView);
        super.onPause();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
        ButterKnife.inject(this, rootView);
        if(WebViewStateHolder.INSTANCE.getBundle() == null)
        {
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader br = null;
            try
            {
                br = new BufferedReader(new InputStreamReader(getActivity().getAssets().open("start.html")));
                String line = null;
                while((line = br.readLine()) != null)
                {
                    stringBuilder.append(line);
                }
            }
            catch(IOException e)
            {
                Log.d(getClass().getName(), "Failed reading HTML.", e);
            }
            finally
            {
                if(br != null)
                {
                    try
                    {
                        br.close();
                    }
                    catch(IOException e)
                    {
                        Log.d(getClass().getName(), "Kappa", e);
                    }
                }
            }
            myWebView
                .loadDataWithBaseURL("file:///android_asset/", stringBuilder.toString(), "text/html", "utf-8", null);
        }
        else
        {
            myWebView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
        }
        return rootView;
    }
}我为WebView的状态制作了Singleton支架。只要存在应用程序进程,状态便会保留。
编辑:这loadDataWithBaseURL不是必需的,它与
    //in onCreate() for Activity, or in onCreateView() for Fragment
    if(WebViewStateHolder.INSTANCE.getBundle() == null) {
        webView.loadUrl("file:///android_asset/html/merged.html");
    } else {
        webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
    }虽然我读过这篇文章,但不一定能与Cookie一起使用。
试试这个
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
    private WebView wv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webView);
        String url = "https://www.google.ps/";
        if (savedInstanceState != null)
            wv.restoreState(savedInstanceState);
        else {
            wv.setWebViewClient(new MyBrowser());
            wv.getSettings().setLoadsImagesAutomatically(true);
            wv.getSettings().setJavaScriptEnabled(true);
            wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            wv.loadUrl(url);
        }
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        wv.saveState(outState);
    }
    @Override
    public void onBackPressed() {
        if (wv.canGoBack())
            wv.goBack();
        else
            super.onBackPressed();
    }
    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}此页面解决了我的问题,但我必须在初始页面中进行一些更改:
    protected void onSaveInstanceState(Bundle outState) {
       webView.saveState(outState);
       }这部分对我来说有一点问题。在第二个方向上,更改应用程序以空指针终止
使用它为我工作:
    @Override
protected void onSaveInstanceState(Bundle outState ){
    ((WebView) findViewById(R.id.webview)).saveState(outState);
}您应该尝试这样:
onServiceConnected方法中,获取WebView并调用该setContentView方法以呈现WebView。我对其进行了测试,但是它不能与其他WebView(例如XWalkView或GeckoView)一起使用。
@Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }