Jetpack Compose自定义搜索框
效果
代码
/** * @param hint: 空字符时的提示 * @param startIcon: 左侧图标; -1 则不显示 * @param iconSpacing: 左侧图标与文字的距离; 相当于: drawablePadding */ @Composable fun CustomEdit( text: String = "", onValueChange: (String) -> Unit, modifier: Modifier, hint: String = "请输入", @DrawableRes startIcon: Int = -1, iconSpacing: Dp = 6.dp, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, visualTransformation: VisualTransformation = VisualTransformation.None, cursorBrush: Brush = SolidColor(MaterialTheme.colorScheme.primary) ) { // 焦点, 用于控制是否显示 右侧叉号 var hasFocus by remember { mutableStateOf(false) } BasicTextField( value = text, onValueChange = onValueChange, modifier = modifier.onFocusChanged { hasFocus = it.isFocused }, singleLine = true, enabled = enabled, readOnly = readOnly, textStyle = textStyle, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, visualTransformation = visualTransformation, cursorBrush = cursorBrush, decorationBox = @Composable { innerTextField -> Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { // -1 不显示 左侧Icon if (startIcon != -1) { Image(painter = painterResource(id = startIcon), contentDescription = null) Spacer(modifier = Modifier.width(iconSpacing)) } Box(modifier = Modifier.weight(1f)) { // 当空字符时, 显示hint if (text.isEmpty()) Text(text = hint, color = Color.Gray, style = textStyle) // 原本输入框的内容 innerTextField() } // 存在焦点 且 有输入内容时. 显示叉号 if (hasFocus && text.isNotEmpty()) { Icon(imageVector = Icons.Filled.Clear, // 清除图标 contentDescription = null, // 点击就清空text modifier = Modifier.clickable { onValueChange.invoke("") }) } Icon( imageVector = Icons.Filled.Search, contentDescription = null, modifier = Modifier .padding(start = 10.dp) ) } } ) }
使用
CustomEdit( text = searchText, onValueChange = { searchText = it }, hint = "搜索应用", modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, top = 0.dp, end = 16.dp, bottom = 10.dp) .height(50.dp) .background(Color(0xBCE9E9E9), shape = MaterialTheme.shapes.medium) .padding(horizontal = 16.dp), textStyle = Typography.bodyMedium, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), )
作者:冲锋的麦克
出处:https://www.cnblogs.com/zhangwenju/p/16658044.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库