Created
November 11, 2021 14:56
-
-
Save rahulsainani/000749c43dc7149fe85af73e42837fc2 to your computer and use it in GitHub Desktop.
A workaround to make TextField scroll inside a scrolling parent so it doesn't go behind the ime. https://issuetracker.google.com/issues/192043120
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
@Composable | |
private fun ScrollingTextField( | |
text: String, | |
onValueChange: (String) -> Unit, | |
scrollState: ScrollState, | |
) { | |
val interactionSource = remember { MutableInteractionSource() } | |
val interactionSourceState = interactionSource.collectIsFocusedAsState() | |
val coroutineScope = rememberCoroutineScope() | |
val ime = LocalWindowInsets.current.ime | |
val textSize = remember { mutableStateOf(IntSize.Zero) } | |
val previousScrollState = remember { mutableStateOf(scrollState.value) } | |
TextField( | |
value = text, | |
onValueChange = onValueChange, | |
backgroundColor = Theme.colors.surface, | |
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), | |
interactionSource = interactionSource, | |
modifier = Modifier | |
.onGloballyPositioned { textSize.value = it.size } | |
.fillMaxWidth() | |
) | |
LaunchedEffect(ime.isVisible, interactionSourceState.value) { | |
if (interactionSourceState.value) { | |
coroutineScope.launch { | |
if (ime.isVisible) { | |
previousScrollState.value = scrollState.value | |
delay(DELAY_BEFORE_SCROLL_ANIMATION_MS) | |
scrollState.animateScrollTo(ime.bottom + textSize.value.height) | |
} else { | |
delay(DELAY_BEFORE_SCROLL_ANIMATION_MS) | |
scrollState.animateScrollTo(previousScrollState.value) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment