Hey people, I got a compose riddle for you in the ...
# compose
m
Hey people, I got a compose riddle for you in the 🧵
• I have a screen with multiple full-width TextFields in it, organised as a Column, • I want to show the keyboard and give focus to a particular field when first entering the screen: the second field from the top, • The very last field expands as more text is added (
BodyTextField
), • As the last field expands, I want the current line to be always visible and not disappear behind the keyboard, as more text is added. In order to achieve the correct scroll behaviour as the user is typing, I set the reverse scrolling to true on the column. This is roughly the code:
Copy code
@Composable
fun SomeScreen() {
    val maxWidthModifier = Modifier.fillMaxWidth()
    val focusRequester = remember { FocusRequester() }

    Column {
        Column(
            modifier = maxWidthModifier
                .verticalScroll(rememberScrollState(), reverseScrolling = true)
        ) {
            PrefixedEmailTextField(
                prefixStringResource = R.string.from_prefix,
                modifier = maxWidthModifier
            )
            Divider()
            PrefixedEmailTextField(
                prefixStringResource = R.string.to_prefix,
                modifier = maxWidthModifier.focusRequester(focusRequester)
            )
            Divider()
            SubjectTextField(maxWidthModifier)
            Divider()
            BodyTextField()
        }
    }

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}
This works as intended in the portrait, however in the landscape mode: • There’s only space for a single line to be visible above the keyboard when entering the screen, • The correct field is given the focus, however due to reverseScrolling = true param the whole column is scrolled to the very bottom to start with- the focused field is not visible. Any ideas how to keep the scrolling behaviour as described while also showing the focused field in the landscape mode? I tried a couple of hacks but none worked so far.
Seems like https://developer.android.com/reference/kotlin/androidx/compose/foundation/relocation/BringIntoViewRequester is what I needed, in case someone is wondering the same and comes across this question in the future. As a follow up though, it seems like I needed to add an artificial delay to make it work properly and scroll to the focused field. I am guessing it’s something to do with the keyboard being shown?
h
cc: @Zach Klippenstein (he/him) [MOD]
m
Another follow up: the delay was needed because of the keyboard. Luckily, I was able to avoid it by following this response on stack overflow (kudos to the author). So far it seems to do the trick.