Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, nothing happens.

val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    modifier = Modifier.fillMaxWidth(),
    value = textState.value,
    onValueChange = { value : TextFieldValue ->
        textState.value = value
    }
)
like image 589
Mukul jangir Avatar asked Oct 03 '20 07:10

Mukul jangir


People also ask

What is LazyColumn in jetpack compose?

LazyColumn produces a vertically scrolling list, and LazyRow produces a horizontally scrolling list. The Lazy components are different to most layouts in Compose. Instead of accepting a @Composable content block parameter, allowing apps to directly emit composables, the Lazy components provide a LazyListScope.

What is mutableStateOf in jetpack compose?

mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. interface MutableState<T> : State<T> { override var value: T. } Any changes to value will schedule recomposition of any composable functions that read value .

Does jetpack compose use views?

Jetpack Compose is designed to work with the established View-based UI approach. If you're building a new app, the best option might be to implement your entire UI with Compose. But if you're modifying an existing app, you might not want to fully migrate your app all at once.


1 Answers

Posting an updated Answer to the question (APIs were renamed in Compose Beta)

@Composable
fun AutoFocusingText() {
    var value by mutableStateOf("Enter Text")
    val focusRequester = remember { FocusRequester() }
    TextField(
        value = value, 
        onValueChange = { value = it },
        modifier = Modifier.focusRequester(focusRequester)
    )
    
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}
like image 167
Ralston Avatar answered Oct 21 '22 12:10

Ralston