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

       

    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作为整体返回。

     

    程序实例

      附上完整的程序:

    WebView Basic
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    
    @SuppressLint("SetJavaScriptEnabled")
    public class WebActivity extends Activity
    {
        private WebView myWebView = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_web);
    
            // 打开网页
            myWebView = (WebView) findViewById(R.id.webview);
            //
    
            // myWebView.loadUrl("http://www.cnblogs.com/mengdd/");// 博客链接
            myWebView.loadUrl("http://www.baidu.com/");// 百度链接
    
            // JavaScript使能(如果要加载的页面中有JS代码,则必须使能JS)
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
    
            // 在WebView中打开链接(默认行为是使用浏览器,设置此项后都用WebView打开)
            // myWebView.setWebViewClient(new WebViewClient());
            // 这样设置后所有的链接都会在当前WebView中打开
    
            // 更强的打开链接控制:自己覆写一个WebViewClient类:除了指定链接从WebView打开,其他的链接默认打开
            myWebView.setWebViewClient(new MyWebViewClient());
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            getMenuInflater().inflate(R.menu.activity_web, menu);
            return true;
        }
    
        /**
         * 自定义的WebViewClient类,将特殊链接从WebView打开,其他链接仍然用默认浏览器打开
         * 
         * @author 1
         * 
         */
        private class MyWebViewClient extends WebViewClient
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                if (Uri.parse(url)
                        .getHost()
                        .equals("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html")
                        || Uri.parse(url).getHost()
                                .equals("http://music.baidu.com/"))
                {
                    // This is my web site, so do not override; let my WebView load
                    // the page
    
                    // 这是官网上的例子,但是我点击特定链接的时候仍然是用浏览器而不是用自己的WebView打开,加上下面这句view.loadUrl(url)仍然是用浏览器,无解,不知道哪里出了问题
                    // view.loadUrl(url);
                    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中查看网页时,按返回键的时候按浏览历史退回,如果不做此项处理则整个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);
        }
    
    }

    参考资料

      因为关于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

     

  • 相关阅读:
    VS2010 error LNK2019: 无法解析的外部符号
    strspn()函数的使用方法
    直接插入排序
    opecv 常用的函数
    matlab中 fprintf 和disp的用法
    面试经历
    挚爱 泰戈尔
    见与不见
    无题
    Cannot create PoolableConnectionFactory (Could not create connection to database server.
  • 原文地址:https://www.cnblogs.com/mengdd/p/2938295.html
Copyright © 2011-2022 走看看