一 使用anko库方便开发
implementation "org.jetbrains.anko:anko:$anko_version"
二 要加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
三 加注解@JavascriptInterface
package com.example.user.hellokotlin
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val mWebView by lazy{
wv_WebView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mWebView.settings.javaScriptEnabled=true;
mWebView.webViewClient=MyWebViewClient();
mWebView.webChromeClient=MyWebChromeClient();
mWebView.loadUrl("http://192.25.102.167:8080/main.html")
mWebView.addJavascriptInterface(JsInterface(this),"jsInterface")
}
}
class JsInterface{
var mContext:Context?=null;
constructor(context: Context){
this.mContext=context;
}
@JavascriptInterface
fun showToast(json: String): Unit {
Toast.makeText(mContext,json,Toast.LENGTH_SHORT).show();
}
}
class MyWebViewClient:WebViewClient(){
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
}
}
class MyWebChromeClient:WebChromeClient(){
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
}
}