webview与kotlin相互调用

调用本地HTML示范

1595306906(1).png

js调用kotlin(assert中的html)




    
    Carson






中间桥梁类(js调用kotlin的时候规范test)

class JavaScriptMe {

    private var mContext : Context ?= null

    constructor(mContext: Context?) {
        this.mContext = mContext
    }

    @JavascriptInterface
    fun showToast(json:String){
        mContext?.let {
            it.toast(json)
        }
    }
}

具体调用

class MainActivity : AppCompatActivity() {

    private val mWebView:WebView by lazy {
        tv
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setWebView()

    }

    var setWebView = {
        //开启Kotlin与H5通信的开关
        mWebView.settings.javaScriptEnabled = true
        //设置2个WebViewClient
        mWebView.webViewClient = MyWebView()
        mWebView.webChromeClient = MyWebViewSec();

        //H5与kotlin 通信方式
        //1.h5调用kotlin
        //设置通信桥梁类
        mWebView.addJavascriptInterface(JavaScriptMe(this),"test")


        mWebView.loadUrl("file:///android_asset/test.html");
    }

    private inner class MyWebView : WebViewClient(){

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            //kotlin调用js
            //JS定义String变量的时候用单引号,而JAVA是使用双引号。
            var json = "kotlin调用js"
            mWebView.loadUrl("javascript:showMessage('$json')")
        }
    }

    private class MyWebViewSec : WebChromeClient(){
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
        }
    }
}

callback机制

桥梁(js决定方法名)

class JavaScriptMe {

    private var mContext : Context ?= null

    private var mWebView : WebView ?= null

    constructor(mContext: Context?,mWebView: WebView?) {
        this.mContext = mContext
        this.mWebView = mWebView
    }

    @JavascriptInterface
    fun showToast(json:String){
        mContext?.let {
            it.toast(json)
        }
    }

    //callback (js嗲用kotlin)
    @JavascriptInterface
    fun getHotelData(method : String){
        var d = "获取酒店的数据"
        println(d)

//        callback 回传数据
        mContext?.let {
            it.runOnUiThread {
                mWebView?.let {

                    it.loadUrl("javascript:$method('$d')")
                }
            }
        }


    }
}

HTML类




    
    Carson








主体类还是上面单词调用的

你可能感兴趣的:(webview与kotlin相互调用)