Reputation: 31
Here I am trying to open keyboard automatic when activity get started in JetpackCompose, but I am not getting any ways to achieve this success and getting the error below:
As I study more and I found that I cannot use focusRequester.requestFocus()
outside of clickable method, so here I want to know any other way I can achieve this success or cannot open input keyboard automatic, need reason or solution. Thanks.
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun UIEnterName() {
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
LaunchedEffect(Unit)
{
focusRequester.requestFocus()
keyboardController?.show()
}
}
Upvotes: 1
Views: 1299
Reputation: 194
Solution by Megh Lath throws exception in current compose. This works for now :D
/**
* Better be called on top of the screen otherwise multiple calls can happened
*/
@Composable
fun rememberRequestFocusOnStart(): FocusRequester {
val focusRequester = remember { FocusRequester() }
val requested = remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
while (!requested.value){
try {
focusRequester.requestFocus()
requested.value = true
} catch (e: Exception) {
delay(100)
}
}
}
return focusRequester
}
Upvotes: 0
Reputation: 2204
You don't actually need to call keyboardController?.show()
in LaunchedEffect()
, it will show-up directly when you request focus for any textfield. Checkout below sample code:
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
//Need to hide keyboard when we navigate or pop back
DisposableEffect(key1 = Unit, effect = {
onDispose {
keyboardController?.hide()
}
})
LaunchedEffect(key1 = Unit, block = {
focusRequester.requestFocus()
})
BasicTextField(
value = title,
onValueChange = {
// Your code
},
maxLines = 1,
interactionSource = interactionSource,
modifier = Modifier
.focusRequester(focusRequester)
.padding(top = 40.dp, start = 20.dp, end = 20.dp)
.fillMaxWidth(),
textStyle = //textstyle,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Next
),
cursorBrush = SolidColor(ComposeTheme.colors.primary)
)
This code will open keyboard when this screen launches and hide keyboard when we navigate or pop back
Upvotes: 1