WebView是Android 提供的操作网页的一个组件。

用于浏览网页及其它Internet资源。

这里总结了一些WebView 的经常使用接口。和2个小演示样例程序用于自己开发时直接使用。就不用再去Baidu了。节省点时间。


使用loadUrl和loadData

WebView.loadUrl:打开URL页面(本地或远端)。

WebView.goForward:实现浏览器的前进功能。

WebView.goBack:实现浏览器的回退功能。

WebView.loadData:载入HTML数据。

演示样例程序 1:使用WebView.loadUrl 浏览网页

Layout file:

<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"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <EditText
android:id="@+id/etUrl"
android:layout_width="240dip"
android:layout_height="wrap_content"
android:text="www.sina.com.cn" >
</EditText> <Button
android:id="@+id/btnGo"
android:layout_width="80dip"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" > <Button
android:id="@+id/btnGoForward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward" /> <Button
android:id="@+id/btnGoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout> <WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>

MainActivity.java

package com.example.internet_webview;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends Activity
{
private WebView m_Webview;
private Button m_Go;
private EditText m_Url; private Button m_GoForward;
private Button m_GoBack; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); m_Webview = (WebView) findViewById(R.id.webview);
m_Url = (EditText) findViewById(R.id.etUrl);
m_Go = (Button) findViewById(R.id.btnGo); m_GoForward = (Button) findViewById(R.id.btnGoForward);
m_GoBack = (Button) findViewById(R.id.btnGoBack); m_Webview.setWebViewClient(new WebViewClient(){}); m_Go.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
m_Webview.loadUrl(m_Url.getText().toString());
}
}); m_GoForward.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (m_Webview.canGoForward())
m_Webview.goForward();
}
}); m_GoBack.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (m_Webview.canGoBack())
m_Webview.goBack();
}
});
}
}

演示样例程序 2:使用WebView.loadData解析HTML

在输入栏中 网址变成了HTML代码,这时使用LoadData能够把HTML代码解析出来

MainActivity.hava

package com.example.internet_webview_loaddata;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends Activity
{
private WebView m_Webview;
private Button m_Go;
private EditText m_Url; private Button m_GoForward;
private Button m_GoBack; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); m_Webview = (WebView) findViewById(R.id.webview);
m_Url = (EditText) findViewById(R.id.etUrl);
m_Go = (Button) findViewById(R.id.btnGo); m_GoForward = (Button) findViewById(R.id.btnGoForward);
m_GoBack = (Button) findViewById(R.id.btnGoBack); m_Webview.setWebViewClient(new WebViewClient(){}); String customHtml = "<html><body><h1>Hello</h1></body></html>";
m_Url.setText(customHtml); m_Go.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
m_Webview.loadData(m_Url.getText().toString(), "text/html", "UTF-8");
}
}); m_GoForward.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (m_Webview.canGoForward())
m_Webview.goForward();
}
}); m_GoBack.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (m_Webview.canGoBack())
m_Webview.goBack();
}
});
}
}

WebView.loadUrl 与 WebView.loadData 差别

通过两个測试结果能够非常清楚的看到这两个接口使用时的差别,一个是输入的网址。还有一个输入的是网页的代码。

WebView并非一个单纯的能载入URL显示网页的控件。它本身也是一个浏览器的引擎,基于这一点。或许能够加以利用。开发出更有趣的App。


与JavaScript的交互

WebView与JavaScript的交互事实上本质上是WebView中定义的WebClient的浏览器引擎与javascript的交互。浏览器引擎处理javascript的同一时候也提供给Andriod一些接口。使它能够接收到信息而且进行响应。

处理方式:

  • Android代码中实现Javascript接口的处理

    javascript::alert() === WebChromeClient::onJsAlert()

    javascript::confirm() === WebChromeClient::onJsConfirm()

    javascript::prompt() === WebChromeClient::onJsPrompt()

当javascript调用它的函数时,也会触发Android调用响应的接口。

  • Android提供自己定义接口供Javascript使用。

    这里用到的主要是WebChromeClient::addJavascriptInterface()接口。当中实现的一些接口函数能够供javascript程序来调用。

  • Android与Javascript通过消息交互。

    这里使用的是WebChromeClient::onConsoleMessage()接口。它为Android提供了处理javascript日志消息的一种能力。也能够作为消息传递的一种方式。

layout 定义

activity_main.xml,当中基本的就是WebView.

<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"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <EditText
android:id="@+id/etUrl"
android:layout_width="240dip"
android:layout_height="wrap_content"
android:text="www.sina.com.cn" >
</EditText> <Button
android:id="@+id/btnGo"
android:layout_width="80dip"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout> <WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>

js_prompt_layout.xml 弹出对话框时的 layout。

<?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" > <TextView
android:id="@+id/tvTitle"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="JS Called prompt Show Android Dialogue" /> <EditText
android:id="@+id/etJSPrompt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/> </LinearLayout>

JS页面定义和预览

<html>
<head>
<script type="text/javascript">
function doAlert() {
alert("Alert I am from JS!");
} function doConfirm() {
confirm("Confirm from JS");
} function doPrompt()
{
var val = prompt("Prompt from JS, please input");
if (val)
{
document.getElementById('id_name').value = val
}
} function CustimizeFunc()
{
CustimizeAndroidFunc.popupDialogue();
} function ShowReturn()
{
var retResult = CustimizeAndroidFunc.showResult();
var dspList = document.getElementById("DispList"); var div = document.createElement("div");
div.innerHTML = retResult;
dspList.appendChild(div);
}
</script>
</head>
<body background="black">
<input type="button" value="Alert Test" onclick="doAlert()"/><br/><br/>
<input type="button" value="Confirm Test" onclick="doConfirm()"/><br/><br/>
<input type="button" value="Prompt Test" onclick="doPrompt()"/><br/>
<input type="text" id="id_name" name="name_a" /><br/><br/>
<input type="button" value="Custimize Function Popup" onclick="CustimizeFunc()"/><br/><br/>
<input type="button" value="Custimize Function ShowList" onclick="ShowReturn()"/><br/><br/>
<div id="DispList"></div>
</body>
</html>

程序执行结果

MainActivity.java

注意: @JavascriptInterface 在Android较新的版本号中为了防止JS能够通过反射取得Java类全部的接口。在定义接口时添加了一个@JavascriptInterface属性,仅仅有带有这个标志函数才干在JS中被訪问。

package com.example.internet_webview_jswork;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText; @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
public class MainActivity extends Activity
{
private WebView m_Webview;
private WebChromeClient m_Client; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); m_Webview = (WebView) findViewById(R.id.webview); m_Webview.getSettings().setJavaScriptEnabled(true);
m_Client = new WebChromeClient()
{
public boolean onJsAlert(WebView view, String url, String message, final JsResult result)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("JS Call alert and Android show Alert Dialogue")
.setMessage(message)
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
}).create().show();
return true;
} public boolean onJsConfirm(WebView view, String url, String message, final JsResult result)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("JS Call confirm and Android show Confirm Dialogue")
.setMessage(message)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
}).create().show();
return true;
} public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
final JsPromptResult result)
{
LayoutInflater inflater = getLayoutInflater();
View prompt = inflater.inflate(R.layout.js_prompt_layout, null);
final EditText etJSPromptValue = (EditText) prompt.findViewById(R.id.etJSPrompt); new AlertDialog.Builder(MainActivity.this)
.setTitle("JS Call prompt and Android show Prompt Dialogue")
.setView(prompt)
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Here will confirm the Android text to JS
result.confirm(etJSPromptValue.getText().toString());
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
}).create().show();
return true;
}
}; m_Webview.setWebChromeClient(m_Client);
m_Webview.addJavascriptInterface(new Object()
{
@SuppressWarnings("unused")
@JavascriptInterface
public void popupDialogue()
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("JS Call Android popupDialogue")
.setMessage("JS Call Android Custimized function::popupDialogue")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{}
}).create().show();
} @SuppressWarnings("unused")
@JavascriptInterface
public String showResult()
{
String strRet = "I am the message from Android";
return strRet;
} }, "CustimizeAndroidFunc"); m_Webview.loadUrl("file:///android_asset/js_work.html");
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

測试GUI.

測试结果

- 点击红色部分的按钮时,输入在Android对话框中的内容会把值显示在HTML的输入框中。

  • 点击蓝色部分的按钮时Android函数的返回值会被显示到HTML中。

Android Internet - WebView 的使用的更多相关文章

  1. Android中webView的基础使用(一)

    WebView是View的一个子类,可以让你在activity中显示网页. 可以在布局文件中写入WebView:比如下面这个写了一个填满整个屏幕的WebView: <?xml version=& ...

  2. Android在WebView上构建Web应用程序

    原文链接:http://developer.android.com/guide/webapps/webview.html reference:http://developer.android.com/ ...

  3. Android之webview详解

    文章大纲 一.webview基本介绍1.什么是webview2.为什么要使用webview3.webview基本操作 二.webview高级使用1.WebView状态2.资源加载3.WebView加载 ...

  4. Android 使用WebView显示网页

    构建WebView就可以显示Web信息.因为我觉得这里会讲述很多方式来实现WebView,所以我决定为每一种方式创建一个对应的Activity,MainActivity通过Button可以点击进入对应 ...

  5. Android之WebView的使用样例——WebSetting、WebViewClient、WebChromeClient

    点击查看原文 代码直接下载http://download.csdn.net/detail/metis100/8514837 第一步,xml Manifest中要设置网络权限,否则会出先 webpage ...

  6. Cocos2d-x3.3RC0载入Android的WebView

    代码部分摘自http://www.fusijie.com/blog/2013/12/26/play-cocos2dx-33/ Cocos2d-x3.3RC0通过Jni嵌入Android的WebView ...

  7. Android使用WebView打包网页成app

    原生app的开发成本和网页相比相对较高,所以越来越多的app使用网页来作为界面,甚至完全将一个网站封装成app,可以提高开发速度,还能基本实现跨平台. 下面以Android为例,在ubuntu-14. ...

  8. Android中webView和网页的交互

     Android中webView和网页的交互 Android中webView跟网页的交互式通过JavaScript进行的.具体步骤: 1.创建JavaScript,在点击的时候调用JavaScript ...

  9. Android 显示 WebView ,加载URL 时,向webview的 header 里面传递参数

    1.主要布局 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:and ...

随机推荐

  1. 使用javac编译java文件

    过程中遇到的几个问题记录如下: 1.java -version正常显示java版本,但是javac却显示[不是内部外部命令] 原因:JAVA_HOME设置成了用户环境变量,Path里用%JAVA_HO ...

  2. mysql数据库的介绍及安装

    一.什么是数据库 1.什么是数据(Data) 描述事物的符号记录成为数据,描述事物的符号既可以是文字.图片.图像.声音.语言等,数据有多种表现形式,他们都可以经过数字化后存入计算机 在计算机中描述一个 ...

  3. android 将手机号中间隐藏为星号(*)

    ){ StringBuilder sb =new StringBuilder(); ; i < pNumber.length(); i++) { char c = pNumber.charAt( ...

  4. R 连接mysql数据库

    一.配置RODBC 1.R下载RODBC包,安装好.2.在http://dev.mysql.com/downloads/connector/odbc下载mySQL ODBC,安装好.3.windows ...

  5. 三维重建:SLAM相关的一些术语解释

    SLAM是一个工程问题,再次复习一下工程中可能用到的名词解释. 还是不要看了,高翔的科普读物已经出版了,读他的<slam十四讲>就可以了. 一.度量相关: 世界坐标系:描述图像的平面坐标系 ...

  6. 安卓系统使用摄像头API

    原文链接:定制自己的安卓Camera        参考链接:http://blog.csdn.net/tankai19880619/article/details/9075839           ...

  7. Android开发之拍照功能实现

    参考链接:http://www.linuxidc.com/Linux/2013-11/92892p3.htm 原文链接:http://blog.csdn.net/tangcheng_ok/articl ...

  8. python 处理中文 读取数据库输出全是问号

    ref:http://www.cnblogs.com/zhoujie/archive/2013/06/07/problem1.html 1.python连接mssql数据库编码问题 python一直对 ...

  9. luoguP4719 【模板】动态 DP 线段树+树链剖分+矩阵乘法+动态DP

    题目描述 给定一棵n个点的树,点带点权. 有m次操作,每次操作给定x,y,表示修改点x的权值为y. 你需要在每次操作之后求出这棵树的最大权独立集的权值大小. 输入输出格式 输入格式: 第一行,n,m分 ...

  10. 如何查看系统的界面,比如费用申请单的序时簿界面引用的是哪一个ListUi.快捷键alt+shift+d 然后选中该ListUI大框框,就可以看到引用的是哪一个了.

    如何查看系统的界面,比如费用申请单的序时簿界面引用的是哪一个ListUi.快捷键alt+shift+d 然后选中该ListUI大框框,就可以看到引用的是哪一个了.