zoukankan      html  css  js  c++  java
  • WebView基本使用

     WebView是View的一个子类,可以让你在activity中显示网页。

      可以在布局文件中写入WebView:比如下面这个写了一个填满整个屏幕的WebView: 

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

     

      加载一个网页,使用loadUrl()

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.loadUrl(http://www.example.com);
     

      注意要在manifest中加上访问网络的权限:

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

    设置WebView要显示的网页

      设置WevView要显示的网页方法有很多:

      互联网页面直接用: 

    myWebView.loadUrl(“http://www.google.com“);

      本地文件用:

    myWebView.loadUrl(“file:///android_asset/XX.html“);  

      本地文件存放在:assets文件中。

      还可以直接载入html的字符串,如:

    String htmlString = "<h1>Title</h1><p>This is HTML text<br /><i>Formatted in italics</i><br />Anothor Line</p>";
    // 载入这个html页面
    myWebView.loadData(htmlString, "text/html", "utf-8");

    在WebView中使用JavaScript

      如果你想要载入的页面中用了JavaScript,你必须为你的WebView使能JavaScript。

      一旦使能之后,你也可以自己创建接口在你的应用和JavaScript代码间进行交互。

    使能JavaScript

      可以通过getSettings()获得WebSettings,然后用setJavaScriptEnabled()使能JavaScript:

    WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

     

      WebSettings中提供了很多有用的设置。

     

     

    处理页面浏览

      当用户点击了你的WebView中的一个链接,默认的行为是Android启动一个处理URL的应用,通常,默认的浏览器打开并下载目标URL。

      但是,你可以在你的WebView中覆盖这一行为,使得连接仍在你的WebView中打开。

      之后,根据在WebView中维护的网页浏览历史,你可以允许用户向前或向后浏览他们的网页。

    在WebView中打开所有链接

      要打开用户点击的链接,只需要用setWebViewClient()方法向你的WebView提供一个WebViewClient 比如:

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new WebViewClient());

     

      此时就OK了, 就可以在你的WebView中打开链接了。

    关于打开链接位置的更多控制

      如果你对在哪里打开链接需要更多的控制,你可以创建自己的类,继承 WebViewClient,然后覆写shouldOverrideUrlLoading() 方法。

      比如下面这个:

    复制代码
        private class MyWebViewClient extends WebViewClient
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
    
           if(Uri.parse(url).getHost().equals(www.example.com))
    { // This is my web site, so do not override; let my WebView load // the page return false; } // Otherwise, the link is not for a page on my site, so launch // another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }
    复制代码

     

      将特定的链接用自己的WebView打开,其他链接用浏览器(intent启动了默认的处理URL的Activity)。

      定义完之后把这个类的对象传入setWebViewClient()方法即可。 

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new MyWebViewClient());

      实践验证:在直接设置setWebViewClient(new WebViewClient());时验证正确,即所有链接都是在WebView中打开。

      在设置为自定义的WebViewClient子类对象时,发现链接仍然都是从默认浏览器中打开。

    浏览网页历史回退

      当你的WebView覆写了URL载入的行为,它会自动地对访问过的网页积累一个历史,你可以利用 goBack() 和 goForward()方法在这个历史中前进或后退。

      比如说使用后退键进行网页后退:

    复制代码
        /**
         * 按键响应,在WebView中查看网页时,按返回键的时候按浏览历史退回,如果不做此项处理则整个WebView返回退出
         */
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            // Check if the key event was the Back button and if there's history
            if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
            {
                // 返回键退回
                myWebView.goBack();
                return true;
            }
            // If it wasn't the Back key or there's no web page history, bubble up
            // to the default
            // system behavior (probably exit the activity)
            return super.onKeyDown(keyCode, event);
        }
    复制代码

     

      canGoBack() 方法在网页可以后退时返回true。

      类似的,canGoForward()方法可以检查是否有可以前进的历史记录。

      如果你不执行这种检查,一旦 goBack() 和 goForward()方法到达历史记录顶端,它们将什么也不做。

      如果不加这种设置,在用户按下Back键时,如果是WebView显示网页,则会将WebView作为整体返回。

     

    程序实例

      附上完整的程序:

     

      1 WebView Basic
      2 
      3 import android.annotation.SuppressLint;
      4 import android.app.Activity;
      5 import android.content.Intent;
      6 import android.net.Uri;
      7 import android.os.Bundle;
      8 import android.view.KeyEvent;
      9 import android.view.Menu;
     10 import android.webkit.WebSettings;
     11 import android.webkit.WebView;
     12 import android.webkit.WebViewClient;
     13 
     14 @SuppressLint("SetJavaScriptEnabled")
     15 public class WebActivity extends Activity
     16 {
     17     private WebView myWebView = null;
     18 
     19     @Override
     20     public void onCreate(Bundle savedInstanceState)
     21     {
     22         super.onCreate(savedInstanceState);
     23         setContentView(R.layout.activity_web);
     24 
     25         // 打开网页
     26         myWebView = (WebView) findViewById(R.id.webview);
     27         //
     28 
     29         // myWebView.loadUrl("http://www.cnblogs.com/mengdd/");// 博客链接
     30         myWebView.loadUrl("http://www.baidu.com/");// 百度链接
     31 
     32         // JavaScript使能(如果要加载的页面中有JS代码,则必须使能JS)
     33         WebSettings webSettings = myWebView.getSettings();
     34         webSettings.setJavaScriptEnabled(true);
     35 
     36         // 在WebView中打开链接(默认行为是使用浏览器,设置此项后都用WebView打开)
     37         // myWebView.setWebViewClient(new WebViewClient());
     38         // 这样设置后所有的链接都会在当前WebView中打开
     39 
     40         // 更强的打开链接控制:自己覆写一个WebViewClient类:除了指定链接从WebView打开,其他的链接默认打开
     41         myWebView.setWebViewClient(new MyWebViewClient());
     42 
     43     }
     44 
     45     @Override
     46     public boolean onCreateOptionsMenu(Menu menu)
     47     {
     48         getMenuInflater().inflate(R.menu.activity_web, menu);
     49         return true;
     50     }
     51 
     52     /**
     53      * 自定义的WebViewClient类,将特殊链接从WebView打开,其他链接仍然用默认浏览器打开
     54      * 
     55      * @author 1
     56      * 
     57      */
     58     private class MyWebViewClient extends WebViewClient
     59     {
     60         @Override
     61         public boolean shouldOverrideUrlLoading(WebView view, String url)
     62         {
     63             if (Uri.parse(url)
     64                     .getHost()
     65                     .equals("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html")
     66                     || Uri.parse(url).getHost()
     67                             .equals("http://music.baidu.com/"))
     68             {
     69                 // This is my web site, so do not override; let my WebView load
     70                 // the page
     71 
     72                 // 这是官网上的例子,但是我点击特定链接的时候仍然是用浏览器而不是用自己的WebView打开,加上下面这句view.loadUrl(url)仍然是用浏览器,无解,不知道哪里出了问题
     73                 // view.loadUrl(url);
     74                 return false;
     75             }
     76             // Otherwise, the link is not for a page on my site, so launch
     77             // another Activity that handles URLs
     78             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     79             startActivity(intent);
     80             return true;
     81         }
     82     }
     83 
     84     /**
     85      * 按键响应,在WebView中查看网页时,按返回键的时候按浏览历史退回,如果不做此项处理则整个WebView返回退出
     86      */
     87     @Override
     88     public boolean onKeyDown(int keyCode, KeyEvent event)
     89     {
     90         // Check if the key event was the Back button and if there's history
     91         if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
     92         {
     93             // 返回键退回
     94             myWebView.goBack();
     95             return true;
     96         }
     97         // If it wasn't the Back key or there's no web page history, bubble up
     98         // to the default
     99         // system behavior (probably exit the activity)
    100         return super.onKeyDown(keyCode, event);
    101     }
    102 
    103 }

    参考资料

      因为关于Web方面完全是个小白,所以别人向我推荐的一个学习网站:

      http://www.w3school.com.cn/

      API Guides:  Building Web Apps in WebView

      http://developer.android.com/guide/webapps/webview.html

      其他学习链接:

      http://www.cnblogs.com/aimeng/archive/2012/05/24/2516547.html

      http://www.apkbus.com/android-44567-1-1.html

    来自: http://www.cnblogs.com/mengdd/archive/2013/03/01/2938295.html

  • 相关阅读:
    递归和this指向
    作用域,闭包
    三种存储方式
    事件流,冒泡,捕获,事件委托
    centos添加登陆成功提示消息
    centos7下安装oracle11g R2报错
    linux下从home分区扩展到根分区
    linux下搭建mongodb副本集
    linux服务下使用nginx之后数据导出超时
    linux下搭建git服务器
  • 原文地址:https://www.cnblogs.com/code4app/p/4632376.html
Copyright © 2011-2022 走看看