Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android和js交互

Android和js交互

編輯:關於Android編程

首先要設置支持javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
設置接口方法,創建接口,接口名可以隨便取,但是在HTML文件中必須一致
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

private class DemoJavaScriptInterface {
    public DemoJavaScriptInterface() {
    }

    public void clickOnAndroid() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

            }
        });
    }
}

HTML文件中對應的點擊方法聲明如下:


加載HTML文件
mWebView.loadUrl("file:///android_asset/index.html");

這裡寫代碼片* 創建兩個對應的Client類,進行處理

mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setWebChromeClient(new MyWebChromeClient());

private class MyWebViewClient extends WebViewClient {
public MyWebViewClient() {
super();
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    return super.shouldOverrideUrlLoading(view, request);
}

@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);
}

@Override
public void onLoadResource(WebView view, String url) {
    super.onLoadResource(view, url);
}

}

private class MyWebChromeClient extends WebChromeClient {

public MyWebChromeClient() {
    super();
}

@Override
public void onProgressChanged(WebView view, int newProgress) {
    super.onProgressChanged(view, newProgress);
}

@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
    return super.onJsAlert(view,url,message,result);
}

@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
    return super.onJsConfirm(view,url,message,result);
}

@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
    return super.onJsPrompt(view, url, message, defaultValue, result);
}

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved