Created
July 18, 2020 05:00
-
-
Save GrJanKandrac/e1185f4dd5f61f0d2d07c1ffe0cf2023 to your computer and use it in GitHub Desktop.
Your glued-to-bottom-above-ScrollView View will not cover you inputs while opening keyboard
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.graphics.Rect | |
import android.view.View | |
import android.view.ViewTreeObserver | |
import androidx.annotation.Px | |
import androidx.core.view.marginBottom | |
/** | |
* This View will be marked as static on the screen. Every other view - if focused and placed in | |
* scrollable view - will be shown above this view while keyboard is being animated | |
* | |
* For best visual experience it is assumed, that this view is statically placed on the | |
* bottom of the screen without any view below it. | |
* | |
* If that's not the case, please use [additionalPadding] parameter to make focused | |
* views to scroll a bit higher | |
*/ | |
fun View.setStatic(@Px additionalPadding: Int = 0) { | |
rootView.setOnApplyWindowInsetsListener { _, insets -> | |
val preDrawListener = object : ViewTreeObserver.OnPreDrawListener{ | |
var lastTick = 0L | |
val tickAnimationThreshold = 50 // 20 FPS | |
override fun onPreDraw(): Boolean { | |
val focusedView = rootView.findFocus() ?: return true | |
val vertical = focusedView.height + height + marginBottom + additionalPadding | |
focusedView.requestRectangleOnScreen(Rect(0, 0, focusedView.width, vertical)) | |
val actualTick = System.currentTimeMillis() | |
if (actualTick < (lastTick + tickAnimationThreshold) || lastTick != 0L) { | |
lastTick = actualTick | |
} else { | |
rootView.viewTreeObserver.removeOnPreDrawListener(this) | |
} | |
return true | |
} | |
} | |
rootView.viewTreeObserver.addOnPreDrawListener(preDrawListener) | |
insets | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment