Reputation: 23
I want to hide webview link if the device is not connected to internet. I am using kotlin and android syudio. I am a beginner in android development. My kotlin file is
val myWebView: WebView = findViewById(R.id.ftphnc_url)
myWebView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
url: String?
): Boolean {
view?.loadUrl(url)
return true
}
}
myWebView.loadUrl("http://10.16.100.244/")
myWebView.settings.javaScriptEnabled = true
myWebView.settings.allowContentAccess = true
myWebView.settings.domStorageEnabled = true
myWebView.settings.useWideViewPort = true
myWebView.settings.setAppCacheEnabled(true)
}
Upvotes: 0
Views: 159
Reputation: 1540
Create a function to check for network connectivity and then use it in displaying.
fun Context.isConnectedToNetwork(): Boolean {
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connectivityManager?.activeNetworkInfo?.isConnectedOrConnecting() ?: false
}
Then use the function with an if
statment to display or not
if (context.isConnectedToNetwork()) {
// Show the webview link
} else {
// dont show webview link
}
Official docs: https://developer.android.com/training/monitoring-device-state/connectivity-status-type
Upvotes: 1