Last active
May 15, 2025 11:15
-
-
Save dmersiyanov/1d7e2b54eeb6d84974ee976253a0fda8 to your computer and use it in GitHub Desktop.
Lifecycle-aware observer to change and preserve Android activity softInputMode. https://medium.com/p/79fb70bf2aa8
This file contains hidden or 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.view.Window | |
import android.view.WindowManager | |
import android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleObserver | |
import androidx.lifecycle.OnLifecycleEvent | |
fun Window?.getSoftInputMode(): Int { | |
return this?.attributes?.softInputMode ?: SOFT_INPUT_STATE_UNSPECIFIED | |
} | |
class InputModeLifecycleHelper( | |
private var window: Window?, | |
private val mode: Mode = Mode.ADJUST_RESIZE | |
) : LifecycleObserver { | |
private var originalMode: Int = SOFT_INPUT_STATE_UNSPECIFIED | |
@OnLifecycleEvent(Lifecycle.Event.ON_START) | |
private fun setNewSoftInputMode() { | |
window?.let { | |
originalMode = it.getSoftInputMode() | |
it.setSoftInputMode( | |
when (mode) { | |
Mode.ADJUST_RESIZE -> WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | |
Mode.ADJUST_PAN -> WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | |
} | |
) | |
} | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) | |
private fun restoreOriginalSoftInputMode() { | |
if (originalMode != SOFT_INPUT_STATE_UNSPECIFIED) { | |
window?.setSoftInputMode(originalMode) | |
} | |
window = null | |
} | |
enum class Mode { | |
ADJUST_RESIZE, ADJUST_PAN | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment