Android入门笔记 - 网络通信 - WebKit

今天来接触一下android中自带的浏览器控件 WebView。

先上一张效果图:

    
 

分为上中下三个部分,上面是EditText和Button,中间区域是WebView,下面是一个进度条显示网页加载进度。

1. layout/ activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/et_address"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="url"
            android:singleLine="true" />

        <Button
            android:id="@+id/btn_loadurl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="跳转" />
    </LinearLayout>

    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0" />

</LinearLayout>

2. MainActivity.java :

package com.example.ch8_03_webkit;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";
	private final Activity mActivity = this;
	private Context mContext = this;
	private Button mBtnLoadUrl;
	private WebView mWebView;
	private EditText mEtUrl;
	private ProgressBar mProgressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mEtUrl = (EditText) findViewById(R.id.et_address);
		mBtnLoadUrl = (Button) findViewById(R.id.btn_loadurl);
		mWebView = (WebView) findViewById(R.id.web);
		mProgressBar = (ProgressBar) findViewById(R.id.progress);
		mProgressBar.setVisibility(View.GONE);
		initWebView(mWebView);
		mBtnLoadUrl.setOnClickListener(new LoadurlListener());
	}

    class LoadurlListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String url = mEtUrl.getText().toString();
            if (url != null && !url.equals("")) {
                if (!url.contains("http://") && !url.contains("file:///")) {
                    url = "http://" + url;
                }
                openUrl(url);
            } else {
                showToast("url不能为空");
            }

        }

    }

	private void initWebView(WebView webview) {
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setAllowFileAccess(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
			}
		});

		webview.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				mProgressBar.setProgress(progress);
				if (progress == 100) {
					mProgressBar.setVisibility(View.GONE);
				} else {
					mProgressBar.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				mActivity.setTitle(title);
				super.onReceivedTitle(view, title);
			}

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setTitle("提示对话框");
				builder.setMessage(message);
				builder.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								result.confirm();
							}
						});
				builder.setCancelable(true);
				builder.create();
				builder.show();
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setTitle("可选择对话框");
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.confirm();
					}
				});
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});
				builder.setCancelable(true);
				builder.create();
				builder.show();
				return true;
			}
		});

	}

	@Override
	public void onBackPressed() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();
			return;
		}
		super.onBackPressed();
	}

	private void openUrl(String url) {
		mWebView.loadUrl(url);
	}

	private void showToast(String words) {
		Toast.makeText(mContext, words, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

WebView常用方法:

WebView. loadUrl( String url) : 加载网页

WebView. canGoBack() ,  WebView.goBack()  :判断是否可回退, 网页回退

WebView中可通过 getSetting() 方法获取到设置,可以做网页的相应设置,比如是否相应 javascript,是否可访问文件,设置是否可缩放等等:

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setBuiltInZoomControls(true);

WebView通过设置WebViewClient设置加载网页方式,网页加载完毕,网页开始加载时的动作:

		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
			}
		});

WebView还可通过设置WebChromeClient设置更详细的细致的配置,比如加载进度,html的title,相应js等:

		webview.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				mProgressBar.setProgress(progress);
				if (progress == 100) {
					mProgressBar.setVisibility(View.GONE);
				} else {
					mProgressBar.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				mActivity.setTitle(title);
				super.onReceivedTitle(view, title);
			}

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setTitle("提示对话框");
				builder.setMessage(message);
				builder.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								result.confirm();
							}
						});
				builder.setCancelable(true);
				builder.create();
				builder.show();
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setTitle("可选择对话框");
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.confirm();
					}
				});
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});
				builder.setCancelable(true);
				builder.create();
				builder.show();
				return true;
			}
		});

WebView中的方法太多,大家可以自己去查。

这里需要注意的是,打开本地html文件和服务器上的html文件方式是不一样的:

服务器:  http:// www.baidu.com

本地 :  file:/// android_asset/ test.html


你可能感兴趣的:(android,webkit,webView)