I am trying to implement a searchbar in my Compose app. I have a textfield, which I want to lose focus of and hide the keyboard, when I click outside of the textfield. However, I can't figure out how to do it. I did try to do it this way, which I saw on GitHub.
However, I did some changes. The original solution used this part of code isHintDisplayed = it != FocusState.Active
which seem to be deprecated. So I changed it to isHintDisplayed = it.isFocused != true
which should in theory do the same. If I revert back to older versions of compose and use FocusState.Active, the focus/unfocus works perfectly, but I can't get it to work with my code.
Any ideas?
Here is my code:
@Composable
fun ListScreen(
navController: NavController
) {
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier.fillMaxSize()
) {
Column {
Spacer(modifier = Modifier.height(20.dp))
Image(
painter = painterResource(id = R.drawable.ic_international_pok_mon_logo),
contentDescription = "Cards",
modifier = Modifier
.fillMaxWidth()
.align(CenterHorizontally)
)
SearchBar(
hint = "Search",
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
}
}
}
}
And here is Searchbar:
@Composable
fun SearchBar(
modifier: Modifier = Modifier,
hint: String = "",
onSearch: (String) -> Unit = {}
) {
var text by remember {
mutableStateOf("")
}
var isHintDisplayed by remember {
mutableStateOf(false)
}
Box(modifier = modifier) {
BasicTextField(
value = text,
onValueChange = {
text = it
onSearch(it)
},
maxLines = 1,
singleLine = true,
textStyle = TextStyle(color = Color.Black),
modifier = Modifier
.fillMaxWidth()
.shadow(5.dp, CircleShape)
.background(Color.White, CircleShape)
.padding(horizontal = 20.dp, vertical = 12.dp)
.onFocusChanged {
isHintDisplayed = !it.isFocused
}
)
if(isHintDisplayed) {
Text(
text = hint,
color = Color.LightGray,
modifier = Modifier
.padding(horizontal = 20.dp, vertical = 12.dp)
)
}
}
}