java - Webview - 如何在旋转时停留在当前页面

标签 java android webview

我为我的企业开发了一个网站,我几乎只使用 PHP

所以 Java 语言(和 android studio)对我来说确实是一个新事物。尽管如此,我必须创建一个APK来使用该网站(为了阻止该网站上的android home)

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

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

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

MainActivity.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>

list

 <?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>

最佳答案

为了在旋转之前加载 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. 您需要创建一个 key 来识别已保存的 URL

    私有(private)最终字符串CACHE_URL_KEY = "CACHE_URL";

  2. 每次旋转时都需要保存 URL

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

  3. 您需要检查是否有轮换。如果是,savedInstanceState 不会为 null,因此检索 Url 并加载它。 否则加载默认页面

    if (savedInstanceState != null) { 字符串savedUrl=savedInstanceState.getString(CACHE_URL_KEY); webView.loadUrl(savedUrl); }别的 { webView.loadUrl("https://www.google.com/"); }

  4. 此外,将保存的状态传递给 LoadWeb 方法

关于java - Webview - 如何在旋转时停留在当前页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903111/

相关文章:

android - 如何设置Android进度条的高度?

java - 在 Android 中检测 BLE 设备名称更改

android - 图像是从画廊上传的,而不是通过 webView 从相机上传的

android - 如何在 Android 上监听复杂图片的 onClick 事件

android - Webview 无法在 htc one x 上通过 javascript 加载内容

java - 更改变量但保留它保存?

java - Java如何计算原始数组的长度?

android - 3rd-party Gradle 插件可能是原因

java - 使用 Linux more 命令时 Runtime.getRuntime().exec() 挂起

java - 如何在使用其中一个时锁定类的所有方法?