Skip to content

Instantly share code, notes, and snippets.

@hkitago
Last active December 7, 2022 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkitago/59d167cff9b9e840eceb3a4e2e9d1caa to your computer and use it in GitHub Desktop.
Save hkitago/59d167cff9b9e840eceb3a4e2e9d1caa to your computer and use it in GitHub Desktop.
Enabling Immersive Mode from JavaScript Event on WebView
/*****************************************************************************
* Put <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml
* and <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> in activity_main.xml
****************************************************************************/
package com.hkitago.enablingImmersiveMode
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.webkit.WebView
class MainActivity : Activity() {
private lateinit var webView: WebView
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webview)
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
}
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(WebViewJavaScriptInterface(), "app")
webView.loadUrl("file:///android_asset/index.html")
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) hideSystemUI()
}
private fun hideSystemUI() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false)
window.insetsController?.apply {
hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
} else {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN)
}
}
inner class WebViewJavaScriptInterface {
var handler = Handler()
@JavascriptInterface
fun enableImmersiveMode() {
handler.postDelayed({ hideSystemUI() }, 0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment