Created
July 29, 2022 08:21
-
-
Save abdallaadelessa/4e30448c87ae4b25cab9e33b230ceb1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.SuppressLint | |
import android.view.View | |
import android.view.ViewGroup | |
import android.view.Window | |
import androidx.core.graphics.Insets | |
import androidx.core.view.ViewCompat | |
import androidx.core.view.WindowCompat | |
import androidx.core.view.WindowInsetsCompat | |
import androidx.core.view.WindowInsetsCompat.Type.InsetsType | |
import androidx.core.view.updateLayoutParams | |
import androidx.core.view.updateMargins | |
/** | |
* @author Created by Abdullah Essa on 23.09.21. | |
*/ | |
/** | |
* Apply the given [WindowInsetsCompat.Type] to the window | |
* HINT: This makes the screen scrollable (without scrollable layout in the screen) if the soft keyboard is visible | |
* to the user | |
* @param view the root view of the Activity or the Fragment (e.g.: fragment.getView()). | |
*/ | |
fun Window.applyKeyboardInsets( | |
view: View | |
) = applyInsets( | |
view = view, | |
WindowInsetsCompat.Type.systemBars(), | |
WindowInsetsCompat.Type.ime(), | |
) | |
/** | |
* Apply the given [WindowInsetsCompat.Type] to the window | |
*/ | |
private fun Window.applyInsets( | |
view: View, | |
@InsetsType vararg insetTypes: Int | |
) { | |
@SuppressLint("WrongConstant") | |
@InsetsType val insetTypeMask: Int = insetTypes.fold(0) { total: Int, type: Int -> total or type } | |
WindowCompat.setDecorFitsSystemWindows(this, false) | |
ViewCompat.setOnApplyWindowInsetsListener(view) { v: View, _ -> v.applyInsets(insetTypeMask) } | |
} | |
/** | |
* Apply the given [WindowInsetsCompat.Type] to the view | |
*/ | |
private fun View.applyInsets( | |
@InsetsType typeMask: Int | |
): WindowInsetsCompat? { | |
val rootWindowInsets: WindowInsetsCompat = ViewCompat.getRootWindowInsets(this) ?: return null | |
val insets: Insets = rootWindowInsets.getInsets(typeMask) | |
updateLayoutParams<ViewGroup.MarginLayoutParams> { | |
updateMargins( | |
left = insets.left, | |
top = insets.top, | |
right = insets.right, | |
bottom = insets.bottom | |
) | |
} | |
return WindowInsetsCompat.Builder() | |
.setInsets(typeMask, insets) | |
.build() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment