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()事件。一旦點擊,界面就跳轉,或者做任何你想做的事情