android webView
簡述:
WebView是什麼?有什麼用途?我們先來看一下官方介紹:
A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.
Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:
[html] view plain copy- <uses-permission android:name="android.permission.INTERNET" />
載入網路資源的一般步驟如下:
①在XML文件中引入WebView控制項 ②在Activity中創建WebView實例 ③對WebView進行必要的設置(根據需要) ④載入網路資源 WebView簡單載入網頁 我們按上述步驟簡單地實現載入百度首頁,首先創建XML文件,就是簡單的在相應Activity頁面中引入WebView控制項,如下:[html] view plain copy- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width_="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <WebView
- android:id="@+id/local_webview"
- android:layout_width_="match_parent"
- android:layout_height="match_parent" />
- </LinearLayout>
在Activity中創建WebView實例、載入網路資源比較簡單,我對代碼做了比較詳細地注釋,直接上代碼吧。
[html] view plain copy- public class MainActivity extends AppCompatActivity implements View.OnClickListener {
- private WebView webview;
- private Button btn;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btn = (Button) findViewById(R.id.btn);
- //創建WebView實例
- webview = (WebView) findViewById(R.id.webview);
- btn.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- if (R.id.btn != v.getId())
- return;
- //跳轉到http://www.baidu.com頁面
- webview.loadUrl("http://www.baidu.com");
- }
- }
代碼如下:
[html] view plain copy- public class WebViewActivity extends Activity {
- private WebView webview_in;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.web_activity);
- webview_in = (WebView) findViewById(R.id.webview_in);
- //web資源
- webview_in.loadUrl("http://www.baidu.com");
- //設置WebViewClient客戶端
- webview_in.setWebViewClient(new WebViewClient(){
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- });
- }
- }
①未開啟JavaScript功能 :該瀏覽器未開啟JavaScript功能(在動態圖中點擊「百度知道 」時可以看出提示);
②按返回鍵網頁後退而不是退出瀏覽器的問題 :當我們在「百度知道 」 頁面點擊返回鍵時並沒有回到百度首頁,而是跳轉出了WebViewActivity。 ok,我們先來解決第一個問題:為WebView開啟JavaScript功能。 核心代碼如下:[html] view plain copy- /**
- * 方法描述:啟用支持javascript
- */
- private void openJavaScript() {
- WebSettings settings = webview_in.getSettings();
- settings.setJavaScriptEnabled(true);
- }
②WebView.goBack(): Goes back in the history of this WebView.
解決該問題的核心代碼:[html] view plain copy- /**
- * 方法描述:改寫物理按鍵——返回的邏輯
- *
- * @param keyCode
- * @param event
- * @return
- */
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- if (webview_in.canGoBack()) {
- webview_in.goBack();//返回上一頁面
- return true;
- } else {
- System.exit(0);//退出程序
- }
- }
- return super.onKeyDown(keyCode, event);
- }
- public class WebViewActivity extends Activity {
- private WebView webview_in;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.web_activity);
- webview_in = (WebView) findViewById(R.id.webview_in);
- openJavaScript();
- //web資源
- webview_in.loadUrl("http://www.baidu.com");
- //設置WebViewClient客戶端
- webview_in.setWebViewClient(new WebViewClient() {
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- });
- }
- /**
- * 方法描述:啟用支持javascript
- */
- private void openJavaScript() {
- WebSettings settings = webview_in.getSettings();
- settings.setJavaScriptEnabled(true);
- }
- /**
- * 方法描述:改寫物理按鍵——返回的邏輯
- *
- * @param keyCode
- * @param event
- * @return
- */
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- if (webview_in.canGoBack()) {
- webview_in.goBack();//返回上一頁面
- return true;
- } else {
- System.exit(0);//退出程序
- }
- }
- return super.onKeyDown(keyCode, event);
- }
- }
為了在WebView頂部顯示進度條我們使用ProgressBar控制項。為了顯示進度我們需要用到的方法為setWebChromeClient (WebChromeClient client),該方法就是為了主要輔助WebView處理Javascript的對話框、網站圖標、網站title、載入進度等。它與WebViewClient的區別請看這篇章:WebViewClient與WebChromeClient的區別。OK,廢話不說,接下來就自定義一個WebView,代碼來了!!!
[html] view plain copy- import android.content.Context;
- import android.graphics.Color;
- import android.graphics.drawable.ClipDrawable;
- import android.graphics.drawable.ColorDrawable;
- import android.util.AttributeSet;
- import android.view.Gravity;
- import android.webkit.WebView;
- import android.widget.ProgressBar;
- /**
- * Created by lzy on 2016/9/22.
- */
- public class ProgressWebView extends WebView {
- private ProgressBar progressbar;
- public ProgressWebView(Context context) {
- super(context);
- }
- public ProgressWebView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- }
- public ProgressWebView(Context context, AttributeSet attrs) {
- super(context, attrs);
- initProgressBar(context);
- setWebChromeClient(new WebChromeClient());
- }
- private void initProgressBar(Context context) {
- progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
- progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, dp2px(context, 3), 0, 0));
- //改變progressbar默認進度條的顏色(深紅色)為Color.GREEN
- progressbar.setProgressDrawable(new ClipDrawable(new ColorDrawable(Color.GREEN), Gravity.LEFT, ClipDrawable.HORIZONTAL));
- addView(progressbar);
- }
- @Override
- protected void onScrollChanged(int l, int t, int oldl, int oldt) {
- super.onScrollChanged(l, t, oldl, oldt);
- }
- /**
- * 方法描述:根據手機的解析度從 dp 的單位 轉成為 px(像素)
- */
- public int dp2px(Context context, float dpValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return (int) (dpValue * scale + 0.5f);
- }
- /**
- * 類描述:顯示WebView載入的進度情況
- */
- public class WebChromeClient extends android.webkit.WebChromeClient {
- @Override
- public void onProgressChanged(WebView view, int newProgress) {
- if (newProgress == 100) {
- progressbar.setVisibility(GONE);
- } else {
- if (progressbar.getVisibility() == GONE)
- progressbar.setVisibility(VISIBLE);
- progressbar.setProgress(newProgress);
- }
- super.onProgressChanged(view, newProgress);
- }
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width_="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <com.lzy.webviewdemo.ProgressWebView
- android:id="@+id/progress_webview"
- android:layout_width_="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="12dp" />
- </LinearLayout>
封裝: TinyWebView 進過對上面對WebView的一步一步改進, 現在我們自定義一個WebView---TinyWebView,一個讓其支持App內部顯示資源、支持JavaScript、支持顯示進度條的WebView。OK,上代碼:[html] view plain copy
- package com.lzy.webviewdemo;
- import android.content.Context;
- import android.graphics.Color;
- import android.graphics.drawable.ClipDrawable;
- import android.graphics.drawable.ColorDrawable;
- import android.util.AttributeSet;
- import android.view.Gravity;
- import android.webkit.WebSettings;
- import android.webkit.WebView;
- import android.webkit.WebViewClient;
- import android.widget.ProgressBar;
- /**
- * Created by lzy on 2016/9/22.
- */
- public class TinyWebView extends WebView {
- private ProgressBar progressbar;
- public TinyWebView(Context context) {
- super(context);
- }
- public TinyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- }
- public TinyWebView(Context context, AttributeSet attrs) {
- super(context, attrs);
- initProgressBar(context);
- openJavaScript();
- setWebViewClient(new WebViewClient());
- setWebChromeClient(new WebChromeClient());
- }
- private void initProgressBar(Context context) {
- progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
- progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, dp2px(context, 3), 0, 0));
- //改變progressbar默認進度條的顏色(深紅色)為Color.GREEN
- progressbar.setProgressDrawable(new ClipDrawable(new ColorDrawable(Color.GREEN), Gravity.LEFT, ClipDrawable.HORIZONTAL));
- addView(progressbar);
- }
- /**
- * 方法描述:啟用支持javascript
- */
- private void openJavaScript() {
- WebSettings settings = getSettings();
- settings.setJavaScriptEnabled(true);
- }
- @Override
- protected void onScrollChanged(int l, int t, int oldl, int oldt) {
- super.onScrollChanged(l, t, oldl, oldt);
- }
- /**
- * 方法描述:根據手機的解析度從 dp 的單位 轉成為 px(像素)
- */
- public int dp2px(Context context, float dpValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return (int) (dpValue * scale + 0.5f);
- }
- /**
- * 類描述:顯示WebView載入的進度情況
- */
- public class WebChromeClient extends android.webkit.WebChromeClient {
- @Override
- public void onProgressChanged(WebView view, int newProgress) {
- if (newProgress == 100) {
- progressbar.setVisibility(GONE);
- } else {
- if (progressbar.getVisibility() == GONE)
- progressbar.setVisibility(VISIBLE);
- progressbar.setProgress(newProgress);
- }
- super.onProgressChanged(view, newProgress);
- }
- }
- }
- public class WebViewActivity extends Activity {
- private TextView webviewTitle;
- private TinyWebView progressWebview;
- private String title;
- private String webViewUrl;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.web_activity);
- getData();
- initViews();
- loadData();
- }
- /**
- * 方法描述:接收數據
- */
- private void getData() {
- webViewUrl = getIntent().getStringExtra("webview_url");
- title = getIntent().getStringExtra("webview_title");
- }
- /**
- * 方法描述:初始化WebView
- */
- private void initViews() {
- progressWebview = (TinyWebView) findViewById(R.id.progress_webview);
- webviewTitle = (TextView) findViewById(R.id.text_webView_title);
- //web資源
- progressWebview.loadUrl(webViewUrl);
- }
- /**
- * 方法描述:載入數據
- */
- private void loadData() {
- if (!TextUtils.isEmpty(title))
- webviewTitle.setText(title);
- if (TextUtils.isEmpty(webViewUrl))
- progressWebview.loadUrl(webViewUrl);
- }
- /**
- * 方法描述:改寫物理按鍵——返回的邏輯
- */
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- if (progressWebview.canGoBack()) {
- progressWebview.goBack();//返回上一頁面
- return true;
- } else {
- System.exit(0);//退出程序
- }
- }
- return super.onKeyDown(keyCode, event);
- }
- /**
- * 方法描述:
- *
- * @param activity 發起跳轉的Activity
- * @param webviewUrl WebView的url
- * @param webviewTitle WebView頁面的標題
- */
- public static void skip(Activity activity, String webviewUrl, String webviewTitle) {
- Intent intent = new Intent(activity, WebViewActivity.class);
- intent.putExtra("webview_url", webviewUrl);
- intent.putExtra("webview_title", webviewTitle);
- activity.startActivity(intent);
- }
- }
- WebViewActivity.skip(MainActivity.this,"http://www.baidu.com","百度首頁");
- <!DOCTYPE html >
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <style type="text/css">
- body{ font-size:12px; line-height:24px;}
- .title{font-size:36px;
- color:#ff0000;
- text-align:center;
- margin-top:28px
- }
- .content1{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:18px}
- .contentothers{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:8px}
- .imagecenter{text-align:center;
- margin-top:18px}
- </style>
- </head>
- <body>
- <div class="imagecenter"><img src="images/haha.jpg" /></div>
- <div class="title">打油詩</div>
- <div class="content1">富了投機倒把的</div>
- <div class="contentothers">提了吹牛拍馬的</div>
- <div class="contentothers">樹了弄虛作假的</div>
- <div class="contentothers">苦了奉公守法的</div>
- </body>
- </html>
- public class LocalWebViewActivity extends Activity{
- private WebView localWebview;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.local_webview_activity);
- localWebview = (WebView) findViewById(R.id.local_webview);
- WebSettings settings = localWebview.getSettings();
- settings.setJavaScriptEnabled(true);
- settings.setSupportZoom(true);
- localWebview.loadUrl("file:///android_asset/myhtmlfile.html");
- localWebview.setWebViewClient(new WebViewClient());
- }
- }
- <!DOCTYPE html >
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <style type="text/css">
- body{ font-size:12px; line-height:24px;}
- .title{font-size:36px;
- color:#ff0000;
- text-align:center;
- margin-top:28px
- }
- .content1{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:18px}
- .contentothers{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:8px}
- .imagecenter{text-align:center;
- margin-top:18px}
- </style>
- <script type="text/javascript">
- function invokeAndroidMethod(info) {
- javascript:<span stylex="font-size:18px;"><strong><span stylex="color:#FF0000;">qwert</span></strong></span>.showToast(info);
- }
- </script>
- </head>
- <body>
- <div class="imagecenter"><img id="image" src="images/haha.jpg"
- onclick="invokeAndroidMethod(JS調用Android中的方法!)"/></div>
- <div class="title">打油詩</div>
- <div class="content1">富了投機倒把的</div>
- <div class="contentothers">提了吹牛拍馬的</div>
- <div class="contentothers">樹了弄虛作假的</div>
- <div class="contentothers">苦了奉公守法的</div>
- </body>
- </html>
- public class LocalWebViewActivity extends Activity{
- private WebView localWebview;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.local_webview_activity);
- localWebview = (WebView) findViewById(R.id.local_webview);
- WebSettings settings = localWebview.getSettings();
- settings.setJavaScriptEnabled(true);
- settings.setSupportZoom(true);
- //WebView添加JS要調用的介面,注意參數
- <span stylex="color:#FF0000;"> localWebview.addJavascriptInterface(new JsInterface(),"<span stylex="font-size:18px;"><strong>qwert</strong></span>");</span>
- localWebview.loadUrl("file:///android_asset/myhtmlfile.html");
- localWebview.setWebViewClient(new WebViewClient());
- }
- <span stylex="color:#FF0000;"> /**
- * 介面描述:供JS調用的介面
- */
- public class JsInterface{
- /**
- * 方法描述:彈出一個Toast
- * @param message JS端需要傳遞的參數(也就是要Toast的內容)
- */
- @JavascriptInterface
- public void showToast(String message) {
- Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
- }
- }</span>
- }
- webview.loadUrl("file:///android_asset/myhtmlfile.html");
- WebSettings settings = localWebview.getSettings();
- settings.setJavaScriptEnabled(true);
- webView.loadUrl("javascript:changeTitle(Android調用JS操控HTML界面)");
- <!DOCTYPE html >
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <style type="text/css">
- body{ font-size:12px; line-height:24px;}
- .title{font-size:36px;
- color:#ff0000;
- text-align:center;
- word-wrap:break-word;
- word-break:break-all;
- margin: 0 auto;
- line-height:150%;
- margin-top:28px
- }
- .content1{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:18px}
- .contentothers{font-size:24px;
- color:#ff0000;
- text-align:center;
- margin-top:8px}
- .imagecenter{text-align:center;
- margin-top:18px}
- </style>
- <script type="text/javascript">
- function invokeAndroidMethod(info) {
- javascript:qwert.showToast(info);
- }
- <span stylex="color:#FF0000;"> <strong>function changeTitle(title) {
- document.getElementById(title).innerHTML= title;
- }</strong>
- </span>
- </script>
- </head>
- <body>
- <div class="imagecenter"><img stylex="border:1px #FF0000 solid;"id="image" src="images/haha.jpg" border="2"
- onclick="invokeAndroidMethod(JS調用Android中的方法!)"/></div>
- <div class="title" id="title">打油詩</div>
- <div class="content1">富了投機倒把的</div>
- <div class="contentothers">提了吹牛拍馬的</div>
- <div class="contentothers">樹了弄虛作假的</div>
- <div class="contentothers">苦了奉公守法的</div>
- </body>
- </html>
- /**
- * 類描述:Android調用JS
- * Created by lzy on 2016/9/22.
- */
- public class AndroidInvokeJS extends Activity {
- private Button btn_android_invoke_js;
- private WebView webView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.android_invoke_js);
- btn_android_invoke_js = (Button) findViewById(R.id.btn_android_invoke_js);
- webView = (WebView) findViewById(R.id.wv_android_invoke_js);
- // ①載入HTML文件
- webView.loadUrl("file:///android_asset/myhtmlfile.html");
- // ②設置JavaScript可用
- WebSettings settings = webView.getSettings();
- settings.setJavaScriptEnabled(true);
- btn_android_invoke_js.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // ③調用HTML中用到的JavaScript方法
- webView.loadUrl("javascript:changeTitle(Android調用JS操控HTML界面)");
- }
- });
- }
- }
推薦閱讀:
