wyc
wyc

Reputation: 19

How to select all text when Jetpack Compose OutlinedTextField gets focus

How do I select all text when OutlinedTextField gets focus?

    @Composable
    fun SearchTextField(text:MutableState<String>,trailingIcon: @Composable (() -> Unit)? = null,
                        placeholder: @Composable (() -> Unit)? = {Text(stringResource(R.string.vip_search_hint_sz))},keyboardOptions:KeyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number )){
        OutlinedTextField(value = text.value, onValueChange = {text.value = it},modifier = Modifier
            .padding(top = 5.dp,bottom = 5.dp),placeholder = placeholder,
            trailingIcon = trailingIcon,textStyle = TextStyle(fontSize = 16.sp),singleLine = true,colors = textFieldColors()
        )

Upvotes: 0

Views: 2892

Answers (1)

Mahmoud Afarideh
Mahmoud Afarideh

Reputation: 376

val textFieldState = remember {
    mutableStateOf(TextFieldValue(""))
}

OutlinedTextField(
    value = textFieldState.value,
    onValueChange = { text -> textFieldState.value = text },
    modifier = Modifier
        .onFocusChanged { focusState ->
            if (focusState.isFocused) {
                val text = textFieldState.value.text
                textFieldState.value = textFieldState.value.copy(
                    selection = TextRange(0, text.length)
                )
            }
        }
)

Upvotes: 2

Related Questions