Title:如何通过点击Android的webView中的一个元素打开native的界面(activity)
如何在webView中直接打开native的界面
设置webview支持javascript
- webview.getSettings().setJavaScriptEnabled(true);
添加提供给javascript调用的类对象和接口名字
- webview.addJavascriptInterface(new JavascriptInterface(MyActivity.this), "mynamespace");
供javascript调用的类的代码
- public class JavascriptInterface {
- private Activity activity;
-
- public JavascriptInterface(Activity activity){
- this.activity = activity;
- }
- public void toMyPage(){
- Intent intent = new Intent();
- intent.setClass(activity, AnotherActivity.class);
- activity.startActivity(intent);
- }
- }
为webview添加WebViewClient
- webview.setWebViewClient(new MyWebViewClient(this, browser));
在MyWebViewClient的onPageFinished方法中注入javascript代码
- public class MyWebViewClient extends WebViewClient {
-
- private Context con;
-
- public PTCWebViewClient(Context con, final WebView web){
- this.con = con;
- }
-
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- @Override
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- super.onPageStarted(view, url, favicon);
- }
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- view.loadUrl("javascript:(function(){document.getElementById('snapNSendBtn').onclick=function(){window.ltamtc.toSnapNSend();}})()");
- }
- }
如此一来,每当这个webView加载完一个页面,而且这个页面有ID为“mySourceButton”的元素,那这个元素的点击事件就被修改为用户自定义的暴露给javascript调用的toMyPage()事件。一旦点击,界面就跳转,或者做任何你想做的事情