/** * 全透状态栏 */ protected fun setStatusBarFullTransparent() { if (Build.VERSION.SDK_INT >= 21) {//21表示5.0 val window = window window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = Color.TRANSPARENT } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4 window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) //虚拟键盘也透明 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } }
设置后,mainfest里的windowsoftinputMode设置的值无效,键盘还是会遮挡住布局。
解决方法:在window的content布局加一个布局改变监听。
mChildOfContent.viewTreeObserver.addOnGlobalLayoutListener { this.possiblyResizeChildOfContent() }
完整代码:
class WindowSoftModeAdjustResizeExecutor private constructor(val activity: Activity, private val hasFakeStatusBar: Boolean) { private val mChildOfContent: View private var usableHeightPrevious: Int = 0 private val frameLayoutParams: FrameLayout.LayoutParams init { val content = activity.findViewById<View>(android.R.id.content) as FrameLayout mChildOfContent = content.getChildAt(0) mChildOfContent.viewTreeObserver.addOnGlobalLayoutListener { this.possiblyResizeChildOfContent() } frameLayoutParams = mChildOfContent.layoutParams as FrameLayout.LayoutParams } private fun possiblyResizeChildOfContent() { val usableHeightNow = computeUsableHeight() if (usableHeightNow != usableHeightPrevious) { val usableHeightSansKeyboard = mChildOfContent.rootView.height val heightDifference = usableHeightSansKeyboard - usableHeightNow frameLayoutParams.height = usableHeightSansKeyboard - heightDifference mChildOfContent.requestLayout() usableHeightPrevious = usableHeightNow } } private fun computeUsableHeight(): Int { val r = Rect() mChildOfContent.getWindowVisibleDisplayFrame(r) return if (hasFakeStatusBar) r.bottom - r.top else r.bottom } companion object { // For more information, see https://code.google.com/p/android/issues/detail?id=5497 // To use this class, simply invoke assistActivity() on an Activity that already has its content view set. // CREDIT TO Joseph Johnson (http://stackoverflow.com/users/341631/joseph-johnson) for publishing the original Android solution on stackoverflow.com fun assistActivity(activity: Activity, hasFakeStatusBar: Boolean) { WindowSoftModeAdjustResizeExecutor(activity, hasFakeStatusBar) } } }
在setContentView之后调用
WindowSoftModeAdjustResizeExecutor.assistActivity(this,false)
第二个参数是我app里的沉浸状态栏是假沉浸状态栏,在decorView里加了个和状态栏高度一样的view。