WebView使用总结(应用函数与JS函数互相调用)

1.当只用WebView的时候,最先注意的当然是在配置文件中添加访问因特网的权限;

2.如果访问的页面中有Javascript,必须设置支持Javascript:

Java代码
1webview.getSettings().setJavaScriptEnabled(true);



3.如果希望点击链接由自己处理而不是新开Android的系统browser中响应该链接.给WebView添加一个事件监听对象(WebViewClient)并重写其中的一些方法 shouldOverrideUrlLoading对网页中超链接按钮的响应
Java代码


1mWebView.setWebViewClient(new WebViewClient() {
2/**
3* Show in webview not system webview.
4*/
5public boolean shouldOverrideUrlLoading(WebView view, String url) {
6view.loadUrl(url);
7return super.shouldOverrideUrlLoading(view, url);
8}
9}


这样就保证了每次打开的页面都是在WebView实例中显示运行的;

4.在显示WebView时,点击手机Back时,会完全退出当前Activity,如果想退到历史浏览页面:重写back监听:
Java代码


1public boolean onKeyDown(int keyCode, KeyEvent event) {
2WebView mWebView = (WebView) findViewById(R.id.browser);
3if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
4mWebView.goBack();
5return true;
6}
7return super.onKeyDown(keyCode, event);
8}


5.Android SDK提供了一个schema前缀为"file:///android_asset/".WebView遇到这样的schema,就去当前包中的 assets目录中找内容.如:"file:///android_asset/demo.html"
下面一段代码是对网页中JS的类似Alert()类的函数进行相应的重写响应:
Java代码


001webView.setWebChromeClient(new WebChromeClient() {
002public boolean onJsAlert(WebView view, String url, String message,
003final JsResult result) {
004AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs.this);
005b.setTitle("Alert");
006b.setMessage(message);
007b.setPositiveButton(android.R.string.ok,
008new AlertDialog.OnClickListener() {
009public void onClick(DialogInterface dialog,
010int which) {
011result.confirm();
012}
013});
014b.setCancelable(false);
015b.create();
016b.show();
017return true;
018};
019 
020@Override
021public boolean onJsConfirm(WebView view, String url,
022String message, final JsResult result) {
023AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs.this);
024b.setTitle("Confirm");
025b.setMessage(message);
026b.setPositiveButton(android.R.string.ok,
027new AlertDialog.OnClickListener() {
028public void onClick(DialogInterface dialog,
029int which) {
030result.confirm();
031}
032});
033b.setNegativeButton(android.R.string.cancel,
034new DialogInterface.OnClickListener() {
035public void onClick(DialogInterface dialog,
036int which) {
037result.cancel();
038}
039});
040b.setCancelable(false);
041b.create();
042b.show();
043return true;
044};
045 
046@Override
047public boolean onJsPrompt(WebView view, String url, String message,
048String defaultValue, final JsPromptResult result) {
049final LayoutInflater factory = LayoutInflater
050.from(BrowserJs.this);
051final View v = factory.inflate(
052R.layout.prompt_dialog, null);
053((TextView) v.findViewById(R.id.prompt_message_text))
054.setText(message);
055((EditText) v.findViewById(R.id.prompt_input_field))
056.setText(defaultValue);
057 
058AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs.this);
059b.setTitle("Prompt");
060b.setView(v);
061b.setPositiveButton(android.R.string.ok,
062new AlertDialog.OnClickListener() {
063public void onClick(DialogInterface dialog,
064int which) {
065String value = ((EditText) v
066.findViewById(R.id.prompt_input_field))
067.getText().toString();
068result.confirm(value);
069}
070});
071b.setNegativeButton(android.R.string.cancel,
072new DialogInterface.OnClickListener() {
073public void onClick(DialogInterface dialog,
074int which) {
075result.cancel();
076}
077});
078b.setOnCancelListener(new DialogInterface.OnCancelListener() {
079public void onCancel(DialogInterface dialog) {
080result.cancel();
081}
082});
083b.show();
084return true;
085};
086 
087public void onProgressChanged(WebView view, int newProgress) {
088BrowserJs.this.getWindow().setFeatureInt(
089Window.FEATURE_PROGRESS, newProgress * 100);
090super.onProgressChanged(view, newProgress);
091}
092 
093public void onReceivedTitle(WebView view, String title) {
094BrowserJs.this.setTitle(title);
095super.onReceivedTitle(view, title);
096}
097});
098 
099go.setOnClickListener(new OnClickListener() {
100public void onClick(View view) {
101String url = text.getText().toString();
102webView.loadUrl(url);
103}
104});
105webView.loadUrl("file:///android_asset/index.html");


在上述代码中,用到的prompt_dialog.xml:
Java代码


01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03android:gravity="center_horizontal" android:orientation="vertical"
04android:layout_width="fill_parent" android:layout_height="wrap_content">
05<TextView android:id="@+id/prompt_message_text"
06android:layout_width="fill_parent" android:layout_height="wrap_content" />
07<EditText android:id="@+id/prompt_input_field"
08android:layout_width="fill_parent" android:layout_height="wrap_content"
09android:selectAllOnFocus="true" android:scrollHorizontally="true"
10android:minWidth="250dp" />
11</LinearLayout>


还有assets中的Html文件:
Java代码


01<html>
02<script type="text/javascript">
03function onAlert(){
04alert("This is a alert sample from html");
05}
06function onConfirm(){
07var b=confirm("are you sure to login?");
08alert("your choice is "+b);
09}
10function onPrompt(){
11var b=prompt("please input your password","aaa");
12alert("your input is "+b);
13}
14</script>
15<pre>
16<input type="button" value="alert"/>
17<input type="button" value="confirm"/>
18<input type="button" value="prompt"/>
19 
20<a href="http://www.google.com"/>Google</a>
21</pre>
22</html>


接着上篇:
6.通过字符串拼凑的html页面显示:
Java代码


01public void simpleJsClick() {
02WebView webView = (WebView) findViewById(R.id.webview);
03String html = "<html>"
04+ "<body>"
05+ "图书封面<br>"
06+ "<table width='200' border='1' >"
07+ "<tr>"
08+ "<td><a onclick='alert(\"Java Web开发速学宝典\")' ><img style='margin:10px' src='http://images.china-pub.com/ebook45001-50000/48015/cover.jpg' width='100'/></a></td>"
09+ "<td><a onclick='alert(\"大象--Thinking in UML\")' ><img style='margin:10px' src='http://images.china-pub.com/ebook125001-130000/129881/zcover.jpg' width='100'/></td>"
10+ "</tr>"
11+ "<tr>"
12+ "<td><img style='margin:10px' src='http://images.china-pub.com/ebook25001-30000/27518/zcover.jpg' width='100'/></td>"
13+ "<td><img style='margin:10px' src='http://images.china-pub.com/ebook30001-35000/34838/zcover.jpg' width='100'/></td>"
14+ "</tr>" + "</table>" + "</body>" + "</html>";
15 
16webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
17webView.getSettings().setJavaScriptEnabled(true);
18webView.setWebChromeClient(new WebChromeClient());
19}


7.在同种分辨率的情况下,屏幕密度不一样的情况下,自动适配页面:
Java代码


1DisplayMetrics dm = getResources().getDisplayMetrics();
2int scale = dm.densityDpi;
3if (scale == 240) { //
4webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
5} else if (scale == 160) {
6webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);
7} else {
8webView.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
9}


8.判断加载的页面URL地址是否正确:
Java代码


1if(URLUtil.isNetworkUrl(url)==true)


9.设置WebView的一些缩放功能点:
Java代码


1webView.getSettings().setJavaScriptEnabled(true);
2webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
3webView.setHorizontalScrollBarEnabled(false);
4webView.getSettings().setSupportZoom(true);
5webView.getSettings().setBuiltInZoomControls(true);
6webView.setInitialScale(70);
7webView.setHorizontalScrollbarOverlay(true);


完成java文件:
Java代码


01public class MethodMutual extends Activity {
02 
03private WebView mWebView;
04private Handler mHandler = new Handler();
05private static final String LOG_TAG = "WebViewDemo";
06 
07/** Called when the activity is first created. */
08@Override
09public void onCreate(Bundle savedInstanceState) {
10super.onCreate(savedInstanceState);
11setContentView(R.layout.main);
12loadAssetHtml();
13}
14 
15public void loadAssetHtml() {
16mWebView = (WebView) findViewById(R.id.webview);
17WebSettings webSettings = mWebView.getSettings();
18webSettings.setSavePassword(false);
19webSettings.setSaveFormData(false);
20webSettings.setJavaScriptEnabled(true);
21webSettings.setSupportZoom(false);
22mWebView.setWebChromeClient(new MyWebChromeClient());
23// 将一个java对象绑定到一个javascript对象中,javascript对象名就是interfaceName,作用域是Global.
24mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
25mWebView.loadUrl("file:///android_asset/demo.html");
26// 通过应用中按钮点击触发JS函数响应
27Button mCallJS = (Button) findViewById(R.id.mCallJS);
28mCallJS.setOnClickListener(new OnClickListener() {
29@Override
30public void onClick(View v) {
31mWebView.loadUrl("javascript:wave()");
32}
33});
34}
35 
36private int i = 0;
37 
38final class DemoJavaScriptInterface {
39DemoJavaScriptInterface() {
40}
41/**
42* This is not called on the UI thread. Post a runnable to invoke
43* loadUrl on the UI thread.
44*/
45public void callAndroid() {
46mHandler.post(new Runnable() {
47public void run() {
48if (i % 2 == 0) {
49mWebView.loadUrl("javascript:wave()");
50} else {
51mWebView.loadUrl("javascript:waveBack()");
52}
53i++;
54}
55});
56}
57}
58 
59/**
60* Provides a hook for calling "alert" from javascript. Useful for debugging
61* your javascript.
62*/
63final class MyWebChromeClient extends WebChromeClient {
64@Override
65public boolean onJsAlert(WebView view, String url, String message,
66JsResult result) {
67Log.d(LOG_TAG, message);
68result.confirm();
69return true;
70}
71}
72}


main.xml文件:
Java代码

1<?xml version="1.0" encoding="utf-8"?>
2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3android:orientation="vertical" android:layout_width="fill_parent"
4android:layout_height="fill_parent">
5<Button android:layout_width="wrap_content" android:text="CallJs"
6android:layout_height="wrap_content" android:id="@+id/mCallJS" />
7<WebView android:id="@+id/webview" android:layout_width="fill_parent"
8android:layout_height="fill_parent" />
9</LinearLayout>


demo.html:
Java代码

01<html>
02<script language="javascript">
03/* This function is invoked by the activity */
04function wave() {
05alert("1");
06document.getElementById("droid").src="android_waving.png";
07alert("2");
08}
09/* This function is invoked by the activity */
10function waveBack() {
11alert("1");
12document.getElementById("droid").src="android_normal.png";
13alert("2");
14}
15</script>
16<body>
17<!-- Calls into the javascript interface for the activity -->
18<a><div style="width:80px;
19margin:0px auto;
20padding:10px;
21text-align:center;
22border:2px solid #202020;" >
23<img id="droid" src="android_normal.png"/><br>
24Click me!
25</div></a>
26</body>
27</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值