Webview - 如何在Rotate上保留当前页面

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Webview - 如何在Rotate上保留当前页面相关的知识,希望对你有一定的参考价值。

我为我的企业开发了一个网站,我几乎完全使用php

所以Java语言(和android studio)对我来说真的很新。尽管如此我必须创建一个APK来使用该网站(为了阻止这个网站上的Android主页)

但是当我转动屏幕时,webview会显示主页而不是当前页面。

我做了一些研究,并整合了我在这里看到的:Android - Preventing WebView reload on Rotate

但这不起作用,我不明白为什么我总是回到“Google.com”

main activity.Java

package eu.test.chrome;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView webView;

    SwipeRefreshLayout swipe;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        LoadWeb();

        progressBar.setMax(100);
        progressBar.setProgress(1);


        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });


        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
            }
        });


        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }


            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");
            }


            public void onPageFinished(WebView view, String url) {
                //Don't show ProgressBar
                progressBar.setVisibility(View.GONE);
                //Hide the SwipeRefreshLayout
                swipe.setRefreshing(false);
            }

        });

    }


    /* I integrated what I saw here: https://stackoverflow.com/questions/12131025/android-preventing-webview-reload-on-rotate but that does not work
    @Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }*/


    public void LoadWeb() {

        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setjavascriptEnabled(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.loadUrl("https://www.google.com/");
        swipe.setRefreshing(true);
    }

    @Override
    public void onBackPressed() {

        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rel_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/awv_progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="26dp"
        android:indeterminate="true" />


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.SwipeRefreshLayout>


</LinearLayout>

表现

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eu.test.chrome">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:hardwareAccelerated="false"
        android:configChanges="orientation|screenSize" 
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
答案

试试这个

import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;

import android.support.v4.widget.SwipeRefreshLayout;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Main2Activity extends AppCompatActivity {

    WebView webView;

    SwipeRefreshLayout swipe;
    ProgressBar progressBar;
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);



        LoadWeb();
        progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
        progressBar.setMax(100);
        progressBar.setProgress(1);


        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {


                progressBar.setProgress(progress);
            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                webView.loadUrl("https://stackoverflow.com/questions/47885592/how-to-add-a-progress-loading-bar-in-webview/47885692#47885692");
            }

            public void onLoadResource(WebView view, String url) { //Doesn't work
//                swipe.setRefreshing(true);
            }

            public void onPageFinished(WebView view, String url) {

                //Hide the SwipeReefreshLayout
                progressBar.setVisibility(View.GONE);
                swipe.setRefreshing(false);
            }

        });


    }

    public void LoadWeb() {

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.loadUrl("http://dev.ncryptedprojects.com/bistrostays_v3/");
        swipe.setRefreshing(true);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }

    @Override
    public void onBackPressed() {

        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

}

并在您的清单文件中

<activity android:name=".MainActivity"
   android:configChanges="orientation|screenSize">
     <intent-filter>
       <action android:name="android.intent.action.MAIN" />

       <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
 </activity>
另一答案

为了在旋转前加载Url,您需要进行一些添加。

public class MainActivity extends AppCompatActivity {
WebView webView;

SwipeRefreshLayout swipe;
ProgressBar progressBar;

private final String CACHE_URL_KEY = "CACHE_URL";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
    LoadWeb(savedInstanceState);

    progressBar.setMax(100);
    progressBar.setProgress(1);


    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            webView.reload();
        }
    });


    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            progressBar.setProgress(progress);
        }
    });


    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }


        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.loadUrl("file:///android_asset/error.html");
        }


        public void onPageFinished(WebView view, String url) {
            //Don't show ProgressBar
            progressBar.setVisibility(View.GONE);
            //Hide the SwipeRefreshLayout
            swipe.setRefreshing(false);
        }

    });

}


@Override
protected void onSaveInstanceState(Bundle outState )
{
    outState.putString(CACHE_URL_KEY,webView.getUrl());
    super.onSaveInstanceState(outState);
}


public void LoadWeb(Bundle savedInstanceState) {

    webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);


    if (savedInstanceState != null) {
        String savedUrl = savedInstanceState.getString(CACHE_URL_KEY);
        webView.loadUrl(savedUrl);
    }else {
        webView.loadUrl("https://www.google.com/");
    }


    swipe.setRefreshing(true);
}

@Override
public void onBackPressed() {

    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        finish();
    }
}

}

以下是制作的步骤:

  1. 您需要创建密钥以标识已保存的URL private final String CACHE_URL_KEY = "CACHE_URL";
  2. 每次旋转时都需要保存URL @Override protected void onSaveInstanceState(Bundle outState ) { outState.putString(CACHE_URL_KEY,webView.getUrl()); super.onSaveInstanceState(outState); }
  3. 您需要检查是否存在旋转。如果是,则savedInstanceState将不为null,因此检索Url并加载它。 Else Load Default页面 if (savedInstanceState != null) { String savedUrl = savedInstanceState.getString(CACHE_URL_KEY); webView.loadUrl(savedUrl); }else { webView.loadUrl("https://www.google.com/"); }
  4. 另外,将保存的状态传递给LoadWeb方法
另一答案

在Android中创建方法,如:

 @JavascriptInterface
 public boolean CallByMobApp(){
 return true;
}

JavaScript中创建调用函数:

$(window).load(function () {

IsCallByMobileApp = false;
try {
      IsCallByMobileApp = app.CallByMobApp();/*Is call by android app*/

} catch (e) {
    IsCallByMobileApp = false;
}
}

根据此方法,您可以管理要打开的页面。

另一答案

您每次都调用LoadWeb方法。您需要检查savedInstanceState == null然后调用LoadWeb。如果savedInstanceState!= null,则不要调用LoadWeb

以上是关于Webview - 如何在Rotate上保留当前页面的主要内容,如果未能解决你的问题,请参考以下文章

Android:得到WebView当前页的html源码

WebView仿原生app页面切换效果

Android 在当前WebView打开页面,判断是不是有

如何在 iOS webview 中获取当前屏幕上的显示文本

android webview中的进度条

WebView 显示空白页