【问题标题】:How to load external webpage in WebView如何在 WebView 中加载外部网页
【发布时间】:2011-11-10 10:19:22
【问题描述】:

我的问题是网页没有加载到 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);
    }   
}

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

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

【问题讨论】:

  • 您好 Gilbou,您的代码在 2.2 中运行
  • 但不是我 :( HTC Wildfire 上都没有,模拟器上也没有……我只是不明白。
  • 好的……现在可以了。但它会启动 Web 浏览器,而不是在 Web 视图中显示页面。
  • 您好,这意味着如果您运行此代码,则浏览器已打开。
  • 你真的需要这个教程链接android webview example

标签: android html android-webview


【解决方案1】:

感谢post,我终于找到了解决方案。代码如下:

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

    }

}

【讨论】:

  • 不错,但我想明智地显示包含页面的网页。是否可以使用 webview?
  • 别忘了添加权限
  • 实际上,为了处理 webview 中的 url,你应该设置一个 webviewclient,如果你没有设置客户端,默认行为是启动一个处理 URL 的应用程序。见this link
  • 启用 java 脚本会使您的应用程序面临潜在的安全问题,我相信当您在代码中使用它时,android sdk 会警告您。除非您可以控制在 webview 中显示的网站,否则不要这样做,并且启用 java 脚本不应被视为简单的解决方案。
  • 未打开此代码.. 显示Webpage not available
【解决方案2】:

试试这个

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"
/>

在您的活动中:

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

更新

webView.setWebViewClient(new WebViewController()); 添加到您的活动中。

WebViewController 类:

public class WebViewController extends WebViewClient {

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

【讨论】:

  • 对不起。似乎我在清单中改变了一些东西,现在它也可以工作了。但是,页面仍然是在网络浏览器中加载的,而不是在网络视图中。
  • 这条线对我有用:webView.getSettings().setJavaScriptEnabled(true);
  • mWebview.getSettings().setJavaScriptEnabled(true);为我工作,我们必须添加这一行
  • 这是一种不好的做法。 shouldOverrideUrlLoading 为 web 视图中加载的所有页面调用。这包括 iFrame,这意味着如果页面加载 iFrame,页面将被 iFrame 替换。在相关的 android 文档页面上不鼓励这样做。
【解决方案3】:
public class WebViewController extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
webView.setWebViewClient(new WebViewController());

【讨论】:

  • 我正在为我的 webview 设置一个自定义 webViewClient。在我定制的 WebViewClient 中,我重载了 shouldOverrideUrlLoading 方法来加载我的 url。我用这个 loc 传递我的 url:webview.loadUrl("URL");
  • 这是一种不好的做法。 shouldOverrideUrlLoading 在 web 视图中加载的所有页面都被调用。这包括 iFrame,这意味着如果页面加载 iFrame,页面将被 iFrame 替换。在相关的 android 文档页面上不鼓励这样做。
【解决方案4】:

请使用此代码:-

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>

MainActivity.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();
    }
}

如果有任何问题询问我,请尝试此代码。

【讨论】:

  • 它有效。但是你错过了两件事。首先,您没有显示需要互联网许可,其次,使用背景图片。谢谢
【解决方案5】:

很简单试试整合这几行代码 首先获取 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");

}

}

试试这个,它会帮助你解决你的问题

【讨论】:

    【解决方案6】:

    只需进入 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");
        }   
    }
    

    【讨论】:

      【解决方案7】:

      我使用了这个很酷的代码。但有一个错误。 “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.
      

      【讨论】:

        【解决方案8】:

        你可以这样做。

        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("Your URL goes here");
        

        【讨论】:

          【解决方案9】:

          试试这个;

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

          【讨论】:

            【解决方案10】:

            在 AndroidManifest.xml 中添加 Internet 权限

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

            在您的布局中:

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

            在你的活动中

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
            
                try {
                    progressDialog = new ProgressDialog(this);
                    url_Api = "https://docs.microsoft.com/en-us/learn";
            
                    webView = this.findViewById(R.id.webView);
            
                        progressDialog.setMessage(getString(R.string.connection_Wait));
                        progressDialog.setIndeterminate(false);
                        progressDialog.setCancelable(true);
                        progressDialog.show();
            
                        LoadUrlWebView( url_Api );
                }catch (Exception e){
                    Log.w(TAG, "onCreate", e);
                }
            }
            
            private void LoadUrlWebView( String url_api ) {
                try {
                    webView.setWebViewClient(new WebViewClient());
                    webView.setWebChromeClient(new MyWebChromeClient( url_api ));
                    webView.getSettings().setJavaScriptEnabled(true);
                    webView.getSettings().setSupportZoom(true);
                    webView.getSettings().setAllowContentAccess(true);
                    webView.getSettings().setBuiltInZoomControls(true);
                    webView.getSettings().setDisplayZoomControls(false);
            
                    webView.loadUrl(url_api);
                } catch (Exception e) {
                    Log.w(TAG, "setUpNavigationView", e);
                }
            }
            
            private class MyWebChromeClient extends WebChromeClient {
                private String urlAccount;
            
                public MyWebChromeClient( String urlAccount ) {
                    this.urlAccount = urlAccount;
                }
            
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    try {
                        //Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress);
                        progressDialog.setMessage(newProgress + "% " + getString(R.string.connection_Wait));
                        if (newProgress < 100 && !progressDialog.isShowing()) {
                            if (progressDialog != null)
                                progressDialog.show();
                        }
                        if (newProgress == 100) {
                            if (progressDialog != null)
                                progressDialog.dismiss();
                        }
                    }catch (Exception e){
                        Log.w( "onProgressChanged", e);
                    }
                }
            
                @Override
                public void onReceivedTitle(WebView view, String title) {
                    super.onReceivedTitle(view, title);
            
                    sharedPreferences = new Shared_Preferences( context );
                    sharedPreferences.setPageWebView(view.getUrl());
                }
            
            }
            

            【讨论】:

            • 请使用英文,因为这是一个只有英文的网站。在这种情况下,只有 3 行需要翻译。
            【解决方案11】:

            添加 WebView 客户端

            mWebView.setWebViewClient(new WebViewClient());
            

            【讨论】:

              【解决方案12】:

              需要添加WebView客户端

              mWebView.setWebViewClient(new WebViewClient() {
              
                 public void onPageFinished(WebView view, String url) {
                      // do your stuff here
                  }
              });
              

              您也可以在 webview 完成加载网页后使用 onPageFinished 来执行任务

              【讨论】:

                【解决方案13】:

                activity_main.xml:

                <?xml version="1.0" encoding="utf-8"?>
                <androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
                    <WebView
                        android:id="@+id/webView"
                        android:layout_width="0dp"
                        android:layout_height="0dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />
                
                </androidx.constraintlayout.widget.ConstraintLayout>
                

                MainActivity.java:

                package com.example.myapplication;
                
                import androidx.appcompat.app.AppCompatActivity;
                
                import android.os.Bundle;
                import android.webkit.WebView;
                import android.webkit.WebViewClient;
                
                public class MainActivity extends AppCompatActivity {
                    private class MyWebViewClient extends WebViewClient {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return true;
                        }
                    }
                    WebView webView;
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                
                        webView = findViewById(R.id.webView);
                        webView .loadUrl("http://www.google.com");
                        webView.setWebViewClient(new MyWebViewClient());
                    }
                }
                

                AndroidManifest.xml:(添加使用权限和 android:usesCleartextTraffic)

                <?xml version="1.0" encoding="utf-8"?>
                <manifest xmlns:android="http://schemas.android.com/apk/res/android"
                    package="com.example.myapplication">
                
                    <uses-permission android:name="android.permission.INTERNET" />
                
                    <application
                        android:usesCleartextTraffic="true"
                        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/Theme.MyApplication">
                        <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>
                

                【讨论】:

                  【解决方案14】:

                  在您的活动类中添加以下方法。这里的浏览器不过是您的 webview 对象。

                  现在您可以轻松查看包含页面的网页。

                  @Override
                  public boolean onKeyDown(int keyCode, KeyEvent event) {
                      if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
                          browser.goBack();
                          return true;
                      }
                      return false;
                  }
                  

                  【讨论】:

                  • 这为 Android 手机底部的“返回”按钮添加了一项功能:它用作“返回”浏览器按钮。
                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多