Skip to content

Instantly share code, notes, and snippets.

@jedsada-gh
Created January 17, 2021 05:58
Show Gist options
  • Save jedsada-gh/780eb21dcf919aebbc97e432cc4d97ca to your computer and use it in GitHub Desktop.
Save jedsada-gh/780eb21dcf919aebbc97e432cc4d97ca to your computer and use it in GitHub Desktop.
webview-activity
typealias WebViewClientUrlCallback = (url: String?) -> Unit
typealias WebChromeClientLoading = (progress: Int) -> Unit
class WebViewActivity : AppCompatActivity() {
private val mWebViewClient: WebViewClient by lazy { WebViewClient() }
private val mWebViewChromeClient: WebChromeClient by lazy { WebChromeClient() }
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
val title = intent.getStringExtra(KEY_TITLE)
initToolbar(toolbar, title)
webView.apply {
isVerticalScrollBarEnabled = false
settings.domStorageEnabled = true
webViewClient = mWebViewClient.apply {
urlCallback = { url -> url?.let { webView.loadUrl(it) } }
}
webChromeClient = mWebViewChromeClient.apply {
progressCallback = { if (it == 100) viewLoading.hide() }
}
settings.javaScriptEnabled = true
intent.getStringExtra(KEY_URL_WEBVIEW)?.let { loadUrl(it) }
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack()
return true
}
return super.onKeyDown(keyCode, event)
}
}
class WebViewClient : WebViewClient() {
var urlCallback: WebViewClientUrlCallback? = null
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
urlCallback?.invoke(url)
return true
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
urlCallback?.invoke(request?.url?.toString())
return true
}
}
class WebChromeClient : WebChromeClient() {
var progressCallback: WebChromeClientLoading? = null
override fun onProgressChanged(view: WebView?, newProgress: Int) {
progressCallback?.invoke(newProgress)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment