WebView组件



1.使用WebView组件实现简单浏览页面

 

package com.example.javascriptwebview;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button open,back,go,zoomin,zoomout,clear;
	private WebView webview;
	private String[] url = new String[]{"http://hao.360.cn/?z1002","http://www.sina.com.cn/","http://sports.sina.com.cn/nba/"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		open = (Button) findViewById(R.id.open);
		back = (Button) findViewById(R.id.back);
		go = (Button) findViewById(R.id.go);
		zoomin = (Button) findViewById(R.id.zoomin);
		zoomout = (Button) findViewById(R.id.zoomout);
		clear = (Button) findViewById(R.id.clear);
		webview = (WebView) findViewById(R.id.webView);
		
		
		
		open.setOnClickListener(new OpenClickListenerImpl());
		back.setOnClickListener(new BackClickListenerImpl());
		go.setOnClickListener(new GoClickListenerImpl());
		zoomin.setOnClickListener(new ZoominClickListenerImpl());
		zoomout.setOnClickListener(new ZoomoutClickListenerImpl());
		clear.setOnClickListener(new ClearClickListenerImpl());
	}
	
	/**
	 * 选择打开的网站
	 */
	public void showDialog(){
		Dialog dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
				.setTitle("请选择浏览的网站")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				})
				.setItems(url, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						webview.loadUrl(url[which]);
					}
				}).create();
		dialog.show();
	}

	/**
	 * 打开
	 * @author olay
	 *
	 */
	 private  class OpenClickListenerImpl implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			showDialog();
		}
	 }
		
	 /**
		 * 后退
		 * @author olay
		 *
		 */
	 private  class BackClickListenerImpl implements View.OnClickListener{

	    @Override
	    public void onClick(View v) {
			if(webview.canGoBack())
				webview.goBack();
					
		}
	 }
				
	 private  class GoClickListenerImpl implements View.OnClickListener{

			@Override
	   public void onClick(View v) {
			if(webview.canGoForward())
				webview.goForward();
							
		}
		 
	 }
	 
	
	 /**
		 * 放大
		 * @author olay
		 *
		 */
	 private  class ZoominClickListenerImpl implements View.OnClickListener{

			@Override
	   public void onClick(View v) {
			webview.zoomIn();
		}
		 
	 }
	 
	 /**
		 * 缩小
		 * @author olay
		 *
		 */
	 private  class ZoomoutClickListenerImpl implements View.OnClickListener{

			@Override
	   public void onClick(View v) {
			webview.zoomOut();			
		}
		 
	 }
	 
	 /**
		 * 清空
		 * @author olay
		 *
		 */
	 private  class ClearClickListenerImpl implements View.OnClickListener{

			@Override
	   public void onClick(View v) {
			webview.clearHistory();	
		}
		 
	 }
}





2.使用WebView加载HTML代码

 

(1)加载html代码

package com.example.webview;

import java.io.UnsupportedEncodingException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	private Button button1,button2;
	private EditText path;
	private WebView webView;
	private String data;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button2= (Button) findViewById(R.id.button2);
		webView = (WebView) findViewById(R.id.webView);
		
		//html代码
		StringBuffer sb = new StringBuffer();
		sb.append("<div>官网实力榜:全胜步行者居榜首 热火第四火箭第八</div>");
		sb.append("<ul>");
		sb.append("<li>1、印第安纳步行者(7胜0负)</li>");
		sb.append("<li>2、圣安东尼奥马刺(6胜1负)</li>");
		sb.append("<li>3、俄克拉荷马城雷霆(5胜1负)</li>");
		sb.append("<li>4、迈阿密热火(4胜3负)</li>");
		sb.append("</ul>");
		data=sb.toString();
		
		button2.setOnClickListener(new butOnClickTHMLImpl());
	}
	

	private class butOnClickTHMLImpl implements View.OnClickListener{

			@Override
			public void onClick(View v) {
				//使用这个方法加载带中文的html内容时会产生乱码
			   //webView.loadData(data.toString(), "text/html", "UTF-8");
				
				//loadDataWithBaseURL不会产生乱码
			   webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
	
			}
		
	}

	
}


 

(2)加载index.html文件

 

assets下新建index.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

</head>

 

<body>

    <div>官网实力榜:全胜步行者居榜首 热火第四火箭第八</div>

    <ul>

       <li>1、印第安纳步行者(7胜0负)</li>

       <li>2、圣安东尼奥马刺(6胜1负)</li>

       <li>3、俄克拉荷马城雷霆(5胜1负)</li>

       <li>4、迈阿密热火(4胜3负)</li>

    </ul>

</body>

</html>


 

 

 

package com.example.webview;

import java.io.UnsupportedEncodingException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	private Button button1,button2;
	private EditText path;
	private WebView webView;
	private String data;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button2= (Button) findViewById(R.id.button2);
		webView = (WebView) findViewById(R.id.webView);
		button2.setOnClickListener(new butOnClickTHMLImpl());
	}
	

	private class butOnClickTHMLImpl implements View.OnClickListener{

			@Override
			public void onClick(View v) {
				//加载index.html
				webView.loadUrl("file:///android_asset/index.html");
	
			}
		
	}

	
}


 





3.使用WebView加载javascript

 

 (1)

Acitivity_main.xml

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

    <TextView

        android:id="@+id/textView1"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/hello" />

    <EditText

        android:id="@+id/path"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="file:///android_asset/index.html" /><!-- 加载index.html界面 -->

    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/button" />

    <WebView

        android:id="@+id/webView"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

    />

 

</LinearLayout>


 

 

 

(2).由于android中的AlertDialog中没有输入框,所以用一下文件定义一个输入框,用了输入内容。再用java代码将该文件绑定到AlertDialog

 

Prompt_view.xml

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

    <TextView

        android:id="@+id/text"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

         />

     <EditText

        android:id="@+id/edit"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:selectAllOnFocus="true"

        android:scrollHorizontally="true"

         />

 

</LinearLayout>

 


 

(3.)MainActivity .java

 

package com.example.webviewdemo;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	private Button mButton;
	private EditText path;
	private WebView mWebView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mButton = (Button) findViewById(R.id.button);
		path = (EditText) findViewById(R.id.path);
		mWebView =(WebView) findViewById(R.id.webView);
		
		//获取WebSettings对象
		WebSettings webSettings=mWebView.getSettings();
		//设置支持javascript脚本
		webSettings.setJavaScriptEnabled(true);
		//设置可以访问文件
		webSettings.setAllowFileAccess(true);
		//设置支持缩放
		webSettings.setBuiltInZoomControls(true);
		
		//设置按钮单击事件监听
		mButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String url=path.getText().toString();
				mWebView.loadUrl(url);
				
			}
		});
		
		//设置WebChromeClient,对网页中javascript代码的各种事件进行处理
		mWebView.setWebChromeClient(new MyWebChromeClient());
	}

	private class MyWebChromeClient extends WebChromeClient{
        /**
         * 处理javascript中的alert
         */
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			Dialog dialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher)
					.setTitle("Alert对话框")
					.setMessage(message)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//单击确定之后,继续执行网页的操作
							result.confirm();
							
						}
					}).create();
			dialog.show();
			return true;
		}
        
		/**
		 * 处理javascript中的confirm
		 */
		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				final JsResult result) {
			Dialog dialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher)
					.setTitle("Confim对话框")
					.setMessage(message)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							 result.confirm();
							
						}
					})
					.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.cancel();
							
						}
					})
					.setCancelable(false)
					.create();
			dialog.show();
			return true;
		}
        
		/**
		 * 处理javascript中的prompt
		 * message为网页中对话框的提示内容
		 * defaultvaule在没有输入时,默认显示的内容
		 */
		@Override
		public boolean onJsPrompt(WebView view, String url, String message,
				String defaultValue, final JsPromptResult result) {
			//获取一个LayoutInflater对象factory,该对象可以指定的xml布局文件生成相应的对象
			LayoutInflater factory=LayoutInflater.from(MainActivity.this);
			//获取自定义的带有输入框的对话框  有TextView和EditText构成
			final View  dialogView=factory.inflate(R.layout.prompt_view, null);
			//设置TextView对应网页中的提示信息
			TextView text=(TextView) dialogView.findViewById(R.id.text);
			text.setText(message);
			//输入框来着网页的默认文字
			EditText edit=(EditText) dialogView.findViewById(R.id.edit);
			edit.setText(defaultValue);
			
			Dialog dialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher)
					.setTitle("Prompt对话框")
					.setView(dialogView)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//单击确定之后,取得输入的值,传给网页处理
							String value = ((TextView)dialogView.findViewById(R.id.edit)).getText().toString();
							result.confirm(value);//处理用户相应结果
						}
					})
					.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.cancel();
							
						}
					})
					.create();
			dialog.show();
			return true;
		}
		
	}

}


 

 

效果:

加载index.html


点击confim对话框



点击ok,浏览搜狐网页


点击prompt对话框,加载prompt_view.xml作为输入框




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值