1. 程式人生 > >簡單的實現 Js和java互動

簡單的實現 Js和java互動

效果:點選img標籤實現圖片的交替顯示,實現需要懂點js,哈哈。

//上程式碼

public class MainActivity extends AppCompatActivity {

    WebView mWebView;
    android.os.Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView)findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        //"demo"是DemoJavaScriptInterface的別名,可以任意取,這是js呼叫java的固定格式
        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"demo");
        mWebView.loadUrl("file:///android_asset/test.html");
        mHandler = new android.os.Handler();
    }

    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            result.confirm();
            return true;
        }
    }

    final class DemoJavaScriptInterface {

        DemoJavaScriptInterface() {

        }

        @JavascriptInterface
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    //呼叫js中wave方法;("javascript:"+js方法)固定寫法
                    mWebView.loadUrl("javascript:wave()");
                }
            });
        }
    }
}

//test.html檔案內容
<html>
<script language="javascript">

		var flag = false;
        function wave() {
        	if(!flag){
        		flag = true;
        		document.getElementById("droid").src="testb.png";
        	}else{
        		flag = false;
        		document.getElementById("droid").src="testa.png";
        	}
        }

</script>
<body>

<!-- window為固定寫法,demo為DemoJavaScriptInterface的別名,clickOnAndroid為DemoJavaScriptInterface的方法-->
<a onClick="window.demo.clickOnAndroid()">
    <div style="width:160px;
            margin:0px auto;
            padding:10px;
            text-align:center;
            border:2px solid #202020;">
        <img id="droid" src="testa.png"/><br>
        Click me!
    </div>
</a>

</body>
</html>
//資源路徑