I need your help. This is the code I have:
val state by viewModel.state.collectAsStateWithLifecycle()
val keyboard = LocalSoftwareKeyboardController.current
val focusRequester = remember { FocusRequester() }
SearchBar(
query = state.searchQuery,
onQueryChange = { viewModel.onSearchQueryChange(it) },
placeholder = { Text(text = "Search Apps") },
onActiveChange = { },
leadingIcon = {
IconButton(onClick = {
if (state.searchQuery.isNotEmpty()) {
viewModel.searchApps(state.searchQuery)
keyboard?.hide()
}
}) {
Icon(imageVector = Icons.Default.Search, contentDescription = null)
}
},
trailingIcon = {
if (state.searchQuery.isNotEmpty()) {
IconButton(onClick = { viewModel.onSearchQueryChange("") }) {
Icon(imageVector = Icons.Default.Clear, contentDescription = null)
}
}
},
onSearch = {
viewModel.searchApps(state.searchQuery)
focusRequester.freeFocus()
keyboard?.hide()
},
active = true,
tonalElevation = 4.dp,
modifier = Modifier
.focusRequester(focusRequester)
.onFocusEvent { focusState ->
Log.d("test2", "Focus State: $focusState")
}
) {
if (state.isLoading && state.apps.isEmpty()) {
LoadingCompose(
isLoading = state.isLoading,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 100.dp)
)
} else {
if (state.searchQuery.isEmpty()) {
Text(text = "Type an app or game name to search...")
} else if (state.error.isNotEmpty()) {
Text(text = state.error)
} else {
LazyColumn {
items(state.apps) { app ->
AppCard(app = app)
}
}
}
}
}
In this code, focusRequester.freeFocus()
is used to deactivate the TextField. You can call this line of code whenever you want to deactivate the TextField. The blinker still blinks meaning the text field is still activated also this is the output for log with tag of “test2” :
2024-05-16 00:51:28.996 8835-8835 test2 com.example.ap D Focus State: Inactive
2024-05-16 00:51:32.916 8835-8835 test2 com.example.ap D Focus State: Active
So once i click on the Text field, it prints Active then i can’t de-active it back to normal…
So once i click on the Text field, it prints Active then i can’t de-active it back to normal…