Request Focus On Textfield In Jetpack Compose
How to auto focus on textfield in jetpack compose. When i click on textfield and start typing on it. Meantime when i click back button,then when i'm try to click on textfield, noth
Solution 1:
Posting an updated Answer to the question (APIs were renamed in Compose Beta)
@ComposablefunAutoFocusingText() {
var value by mutableStateOf("Enter Text")
val focusRequester = remember { FocusRequester() }
TextField(
value = value,
onValueChange = { value = it },
modifier = Modifier.focusRequester(focusRequester)
)
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
}
Solution 2:
With 1.0.x
you can use something like:
var text by remember { mutableStateOf("text") }
// initialize focus reference to be able to request focus programmaticallyval focusRequester = FocusRequester()
Column {
TextField(
value = text,
onValueChange = {
text = it
},
label = { Text("label") },
modifier = Modifier
// add focusRequester modifier
.focusRequester(focusRequester)
)
Then use focusRequester.requestFocus()
. In this way the system grants focus to the component associated with this FocusRequester
.
To have the field automatically focused when the screen appears you can use:
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
To manually grant the focus to the field:
Button(onClick = { focusRequester.requestFocus() }) {
Text("Click to give the focus")
}
Solution 3:
Taken from Compose Unit Tests and applied to TextField Link
@ExperimentalFocus@ComposablefunAutoFocusingText() {
val textState = remember { mutableStateOf(TextFieldValue()) }
val focusState = remember { mutableStateOf(FocusState.Inactive) }
val focusRequester = FocusRequester()
val focusModifier = Modifier.focus()
Row(
modifier = Modifier.focusObserver { focusState.value = it }
) {
val focusRequesterModifier = Modifier.focusRequester(focusRequester)
TextField(
modifier = focusModifier.then(focusRequesterModifier),
value = textState.value,
onValueChange = { value: TextFieldValue ->
textState.value = value
},
)
}
onActive {
focusRequester.requestFocus()
}
}
Edit: Changed Box to Row because Box has been deprecated in '1.0.0-alpha04'
Solution 4:
valfocusRequester= remember { FocusRequester() }
valinputService= LocalTextInputService.current
valfocus= remember { mutableStateOf(false) }
BasicTextField(
value = "value",
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
.focusRequester(focusRequester)
.onFocusChanged {
if (focus.value != it.isFocused) {
focus.value = it.isFocused
if(!it.isFocused) {
inputService?.hideSoftwareKeyboard()
}
}
},
),
LaunchedEffect("") {
delay(300)
inputService?.showSoftwareKeyboard()
focusRequester.requestFocus()
}
Post a Comment for "Request Focus On Textfield In Jetpack Compose"