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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM