Created
November 16, 2022 21:30
-
-
Save Ifeo-A/e538e26eb5f00a706e6823ef147c4652 to your computer and use it in GitHub Desktop.
Search bar component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@OptIn(ExperimentalMaterial3Api::class) | |
@Composable | |
fun SearchBar( | |
modifier: Modifier = Modifier, | |
@StringRes placeholderText: Int = R.string.placholder_text, | |
onSearch: (searchString: String) -> Unit | |
) { | |
var currentText by rememberSaveable { mutableStateOf("") } | |
val focusManager = LocalFocusManager.current | |
Row( | |
modifier = Modifier | |
.clickable { | |
focusManager.clearFocus() | |
} | |
.then(modifier), | |
verticalAlignment = Alignment.CenterVertically, | |
) { | |
TextField( | |
modifier = Modifier | |
.fillMaxWidth(), | |
value = currentText, | |
onValueChange = { currentValue -> | |
currentText = currentValue | |
}, | |
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), | |
keyboardActions = KeyboardActions( | |
onSearch = { | |
focusManager.clearFocus() | |
onSearch(currentText) | |
}), | |
placeholder = { | |
Text(text = stringResource(placeholderText)) | |
}, | |
leadingIcon = { | |
Icon( | |
imageVector = Icons.Outlined.Search, | |
contentDescription = null | |
) | |
}, | |
trailingIcon = { | |
AnimatedVisibility(visible = currentText.isNotEmpty()) { | |
Icon( | |
imageVector = Icons.Outlined.Close, | |
contentDescription = null, | |
modifier = Modifier | |
.clickable { | |
currentText = "" | |
} | |
) | |
} | |
}, | |
singleLine = true, | |
shape = RoundedCornerShape(50), | |
colors = TextFieldDefaults.textFieldColors( | |
textColor = MaterialTheme.colorScheme.secondary, | |
focusedIndicatorColor = Color.Transparent, | |
unfocusedIndicatorColor = Color.Transparent, | |
) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment