- import the assets to your project
- init Webview
binding.webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
setSupportZoom(true)
useWideViewPort = true
builtInZoomControls = true
}
binding.webView.addJavascriptInterface(JsInterface(this@MainActivity), "json_parse")
then load the preview_json.html
webView.loadUrl("file:///android_asset/preview_json.html")
- Load your json file and convert to string
webView.loadUrl("javascript:showJson($str)")
- Save your json
inner class JsInterface(context: Context) {
private val mContext: Context
init {
mContext = context
}
@JavascriptInterface
fun configContentChanged() {
runOnUiThread {
contentChanged = true
}
}
@JavascriptInterface
fun toastJson(msg: String?) {
runOnUiThread { Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show() }
}
// save json string
@JavascriptInterface
fun saveConfig(jsonString: String?) {
runOnUiThread {
contentChanged = false
Toast.makeText(mContext, "verification succeed", Toast.LENGTH_SHORT).show()
}
}
//format failed
@JavascriptInterface
fun parseJsonException(e: String?) {
runOnUiThread {
e?.takeIf { it.isNotBlank() }?.let { alert(it) }
}
}
}