webview与js交互--上篇--js调java

来源:互联网 发布:c 处理sql注入 编辑:程序博客网 时间:2024/06/03 23:38

这篇主要介绍的是js调java。由一个例子开始

布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <include   layout="@layout/public_page_title"/>    <WebView        android:id="@+id/webview"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        /></LinearLayout>

webview设置:

   webview = (WebView) findViewById(R.id.webview);        WebSettings webSettings = webview.getSettings();        //设置WebView属性,能够执行Javascript脚本        webSettings.setJavaScriptEnabled(true);        //设置可以访问文件        webSettings.setAllowFileAccess(true);        //设置支持缩放        webSettings.setBuiltInZoomControls(true);        webSettings.setUseWideViewPort(true);//设定支持viewport        webSettings.setLoadWithOverviewMode(true);        webSettings.setSupportZoom(true);//设定支持缩放        webview.addJavascriptInterface(new JsInteration(),"android");        //加载需要显示的网页        webview.loadUrl(url);        //设置Web视图        webview.setWebViewClient(new webViewClient ());

webviewClient,不使用默认的浏览器。

private class webViewClient extends WebViewClient {        public boolean shouldOverrideUrlLoading(WebView view, String url) {            webview.loadUrl(url);            return true;        }    }

webview中返回键的处理:

 @Override    //设置回退    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法    public boolean onKeyDown(int keyCode, KeyEvent event) {        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {            webview.goBack(); //goBack()表示返回WebView的上一页面            return true;        }        finish();//结束退出程序        return false;    }

流程:
1.android 定义一个接口(类),并声明一个方法
2.android 实现它
3.js调用该接口的方法。

android供js调用的相关类定义:

private class  JsInteration{        @JavascriptInterface        public void book(){            ......        }    }

js只需设置点击事件,调用window.android.book 即可。(其中,android是android实现类JsInteration的别名,可任意取名)

0 0
原创粉丝点击