小编典典

如何在WebView中加载外部网页

html

我的问题是该网页未加载到webview中。

mWebview.loadUrl("http://www.google.com"); 启动网络浏览器…

这是我的活动代码:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Main extends Activity {

    private WebView mWebview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWebview = new WebView(this);
        mWebview.loadUrl("http://www.google.com");
        setContentView(mWebview);
    }   
}

我在清单中添加了所需的权限:

<uses-permission android:name="android.permission.INTERNET" />

阅读 291

收藏
2020-05-10

共1个答案

小编典典

由于这篇文章,我终于找到了解决方案。这是代码:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;

public class Main extends Activity {

    private WebView mWebview ;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mWebview  = new WebView(this);

        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

        mWebview .loadUrl("http://www.google.com");
        setContentView(mWebview );

    }

}
2020-05-10