You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose中实现带圆角与两端图标的自定义搜索框?

实现带圆角及两端图标的搜索栏解决方案

你的现有代码未将搜索栏元素整合到统一的圆角容器中,且TextField默认边框会破坏整体样式,以下是符合预期的实现代码:

@Composable
fun SearchBar() {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .width(277.dp)
            .height(38.dp)
            .background(
                color = Color(0xFFF5F5F5), // 根据需求替换背景色
                shape = RoundedCornerShape(19.dp) // 高度一半实现半圆角
            )
            .padding(horizontal = 12.dp)
    ) {
        // 左侧图标
        Image(
            painter = painterResource(id = R.drawable.elogo),
            contentDescription = "e logo",
            modifier = Modifier
                .size(24.dp)
                .padding(end = 8.dp)
        )
        // 搜索输入框
        TextField(
            value = "",
            onValueChange = {},
            placeholder = { Text("搜索...") },
            modifier = Modifier
                .weight(1f)
                .height(38.dp),
            colors = TextFieldDefaults.colors(
                focusedContainerColor = Color.Transparent,
                unfocusedContainerColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent
            ),
            textStyle = TextStyle(fontSize = 14.sp)
        )
        // 右侧图标
        Image(
            painter = painterResource(id = R.drawable.vector),
            contentDescription = "Vector",
            alpha = 0.5f,
            modifier = Modifier
                .size(19.dp)
                .padding(start = 8.dp)
        )
    }
}

关键修改说明:

  • 给外层Row添加带圆角的背景,实现整个搜索栏的统一圆角样式
  • 让TextField通过weight(1f)填充图标间的剩余空间,保证布局自适应
  • 移除TextField的默认背景和边框,使其与外层容器背景融合
  • 调整图标尺寸和内边距,优化整体布局紧凑度

内容的提问来源于stack exchange,提问作者Baba Yaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:24:33