如何在WebView中加载外部网页

136
我的问题是网页未在 WebView 中加载。 mWebview.loadUrl("http://www.google.com"); 启动了网络浏览器... 这是我的 activity 代码:
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);
    }   
}

我在 Manifest 文件中添加了所需的权限:

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

你好Gilbou,你的代码在2.2中运行正常。 - Dipak Keshariya
但是对我来说不行 :( 在HTC Wildfire上也不行,在模拟器上也不行... 我就是不明白。 - Gilbou
1
好的...现在它可以工作了。但是它启动了网页浏览器,而不是在webview中显示页面。 - Gilbou
你好,这意味着如果你运行这段代码,浏览器将会打开。 - Dipak Keshariya
你真的需要这个教程链接 android webview example - Athira Reddy
15个回答

232

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

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 );

    }

}

17
别忘了添加权限 <uses-permission android:name="android.permission.INTERNET" />。 - DPP
2
实际上,为了处理Webview中的URL,您应该设置一个Webviewclient。如果您没有设置客户端,则默认行为是启动一个处理URL的应用程序。请参见此链接:http://developer.android.com/guide/webapps/webview.html#HandlingNavigation - erdemlal
2
启用 JavaScript 会为您的应用程序带来潜在的安全问题,我相信当您在代码中使用它时,Android SDK 会对此发出警告。除非您可以控制在 Webview 中显示哪些网站,否则不要这样做,并且启用 JavaScript 不应被视为简单的解决方案。 - LostPuppy
2
无法打开此代码.. 显示“网页不可用” - Ranjith Kumar
@RanjithKumar 对我来说可行,但我不得不注释掉结尾的 setContentView(mWebview);,因为它会产生一个不同的错误:指定的子项已经有一个父项。您必须首先在子项的父项上调用 removeView() - gregn3
显示剩余3条评论

47

试试这个

webviewlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/help_webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:scrollbars="none"
/>

在您的Activity中:

WebView webView;
setContentView(R.layout.webviewlayout);
webView = (WebView)findViewById(R.id.help_webview);
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");

更新

在您的Activity中添加webView.setWebViewClient(new WebViewController());

WebViewController类:

public class WebViewController extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

1
抱歉,似乎我在清单文件中更改了一些内容,现在它也可以工作了。但是仍然存在一个问题,页面在网络浏览器中加载,而不是在Webview中加载。 - Gilbou
这行代码对我有用:webView.getSettings().setJavaScriptEnabled(true); - pixparker
1
mWebview.getSettings().setJavaScriptEnabled(true); 对我有用,我们必须添加这行代码。 - neena
这是一种不好的做法。shouldOverrideUrlLoading会被调用来处理webview中加载的所有页面,包括iFrames。这意味着如果页面加载了一个iFrame,那么页面将被iFrame替换。在相关的Android文档页面上,这是不被鼓励的。 - Hack5

19
public class WebViewController extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
webView.setWebViewClient(new WebViewController());

1
我正在为我的webview设置自定义的webViewClient。在我的自定义WebViewClient中,我已经重载了shouldOverrideUrlLoading方法以加载我的url。我正在通过以下方式传递我的url:webview.loadUrl("URL"); - Rahul
这是一种不好的做法。shouldOverrideUrlLoading会被调用来处理webview中加载的所有页面,包括iFrames。这意味着如果页面加载了一个iFrame,那么页面将被iFrame替换。在相关的Android文档页面上,这是不被鼓励的。 - Hack5

13

请使用以下代码:

Main.Xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/background">
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:background="@drawable/top_heading"
        android:id="@+id/rlayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_centerVertical="true" android:layout_centerHorizontal="true"
            android:textColor="#ffffff" android:textSize="22dip"
            android:textStyle="bold" android:layout_height="wrap_content"
            android:text="More Information" android:id="@+id/txtviewfbdisplaytitle" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_below="@+id/rlayout1"
        android:id="@+id/rlayout2">
        <WebView android:id="@+id/webview1" android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0" />
    </RelativeLayout>
</RelativeLayout>

主活动.Java

public class MainActivity extends Activity {
    private class MyWebViewClient extends WebViewClient {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
              view.loadUrl(url);
              return true;
          }
    }
    Button btnBack;
    WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webview=(WebView)findViewById(R.id.webview1);
        webview.setWebViewClient(new MyWebViewClient());
        openURL();
    }

     /** Opens the URL in a browser */
    private void openURL() {
        webview.loadUrl("http://www.google.com");
        webview.requestFocus();
    }
}

如果有任何问题,请尝试使用这段代码并向我提问。


1
它可以工作。但你错过了两件事。首先,你没有显示需要互联网权限,第二,使用背景图片。谢谢。 - Sumon Bappi

6

非常简单,尝试集成这些代码行,首先在Android Manifest文件中获取权限。

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

然后在你的 Activity.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.MainActivity">

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/help_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

/>

</LinearLayout>

然后在您的 MainActivity.java 中编写以下代码

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity{
    private WebView mWebview ;
    String link = "";// global variable
    Resources res;// global variable
    @Override


      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_modernherbal_main);
            mWebview  = (WebView) findViewById(R.id.help_webview);
            WebSettings webSettings = mWebview.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);



        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }


});

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

}

尝试这个,它可以帮助您解决问题


4

只需进入XML文件并给你的webView赋予ID,然后在Java中粘贴以下代码:

   public class Main extends Activity {

private WebView mWebview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Your_layout_file_name);

    mWebview = (WebView)findViewById(R.id.id_you_gave _to_your_wenview_in_xml);
    mWebview.loadUrl("http://www.google.com");
    }   
}

2

我使用了这段很酷的代码,但出现了一个错误。"neterr_cleartext_not_permitted"。当你使用这段代码时,你会遇到这个问题。

我有一个解决方案,你需要在你的AndroidManifest.xml文件中,在Application附近添加以下内容:

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.

1
尝试这个;
webView.loadData("<iframe src='http://www.google.com' style='border: 0; width: 100%; height: 100%'></iframe>", "text/html; charset=utf-8", "UTF-8");

1
你可以这样做。
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("Your URL goes here");

1
添加 WebView 客户端。
mWebView.setWebViewClient(new WebViewClient());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接