我找到了一种解决方法,但它并不是100%的。例如,它没有卡片属性。也许其他人有一些好主意。这是我的解决方案:
@Composable
fun QuerySearch(
modifier: Modifier = Modifier,
query: String,
label: String,
onDoneActionClick: () -> Unit = {},
onClearClick: () -> Unit = {},
onQueryChanged: (String) -> Unit
) {
var showClearButton by remember { mutableStateOf(false) }
TextField(
modifier = modifier
.fillMaxWidth()
.onFocusChanged { focusState ->
showClearButton = (focusState.isFocused)
},
value = query,
onValueChange = onQueryChanged,
label = { Text(text = label) },
textStyle = MaterialTheme.typography.subtitle1,
singleLine = true,
trailingIcon = {
if (showClearButton) {
IconButton(onClick = { onClearClick() }) {
Icon(imageVector = Icons.Filled.Close, contentDescription = "Clear")
}
}
},
keyboardActions = KeyboardActions(onDone = {
onDoneActionClick()
}),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Text
),
colors = TextFieldDefaults.textFieldColors(
cursorColor = MaterialTheme.colors.secondary,
textColor = MaterialTheme.colors.onPrimary,
focusedIndicatorColor = MaterialTheme.colors.secondary,
)
)
}
@Composable
fun <T> AutoCompleteTextView(
modifier: Modifier,
query: String,
queryLabel: String,
onQueryChanged: (String) -> Unit = {},
predictions: List<T>,
onDoneActionClick: () -> Unit = {},
onClearClick: () -> Unit = {},
onItemClick: (T) -> Unit = {},
itemContent: @Composable (T) -> Unit = {}
) {
val view = LocalView.current
val lazyListState = rememberLazyListState()
LazyColumn(
state = lazyListState,
modifier = modifier.heightIn(max = TextFieldDefaults.MinHeight * 6)
) {
val lazyListScope = this
item {
QuerySearch(
query = query,
label = queryLabel,
onQueryChanged = onQueryChanged,
onDoneActionClick = {
view.clearFocus()
onDoneActionClick()
},
onClearClick = {
onClearClick()
}
)
}
item {
if (predictions.count() > 0) {
Card(
elevation = 4.dp,
modifier = Modifier.padding(8.dp),
backgroundColor = Color.White,
shape = RoundedCornerShape(8.dp)
) {
lazyListScope.items(predictions) { prediction ->
Row(
Modifier
.fillMaxWidth()
.clickable {
view.clearFocus()
onItemClick(prediction)
}
.background(MaterialTheme.colors.primaryVariant)
) {
itemContent(prediction)
}
}
}
}
}
}
}
fun <T> LazyListScope.items(items: List<T>) {
this.items(items)
}
这将导致:![地址自动完成](https://istack.dev59.com/4g4mm.webp)