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

如何在Jetpack Compose中仅修改单个侧边的边框宽度?

Jetpack Compose 默认的 Modifier.border() 确实没法单独设置某一侧的边框宽度,要实现你要的单边边框效果,可以试试这两种方法:

方法一:用 drawBehind 自定义绘制边框

直接在 Modifier 里通过绘制逻辑实现左侧带圆角的边框,和原布局的圆角效果匹配:

Row(
    modifier = Modifier
        .background(Color.White, shape = RoundedCornerShape(4.dp)) // 替换成你需要的背景色
        .drawBehind {
            val borderWidth = 4.dp.toPx() // 这里设置左侧边框的宽度
            val cornerRadius = 4.dp.toPx()
            // 绘制左侧带圆角的边框
            drawRoundRect(
                color = Purple3,
                topLeft = Offset(0f, 0f),
                size = Size(borderWidth, size.height),
                cornerRadius = CornerRadius(cornerRadius, 0f) // 仅左上、左下保留圆角
            )
        }
        .padding(horizontal = 10.dp, vertical = 10.dp)
        .padding(start = 14.dp), // 给左侧边框留出显示空间
    verticalAlignment = Alignment.CenterVertically
) {
    Image(
        painter = painterResource(id = R.drawable.info),
        contentDescription = stringResource(id = R.string.long_press_an_item),
    )
    Text(
        text = stringResource(id = R.string.long_press_an_item),
        fontFamily = FontFamily(Font(R.font.inter_medium)),
        fontSize = 12.sp,
        color = Gray5,
        modifier = Modifier.padding(horizontal = 10.dp)
    )
}

方法二:用 Box 嵌套实现更直观的布局

通过外层 Box 提供圆角背景,内层用 Spacer 做左侧边框,逻辑更清晰:

Box(
    modifier = Modifier
        .background(Color.White, shape = RoundedCornerShape(4.dp))
) {
    Row(
        modifier = Modifier.padding(10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 左侧边框
        Spacer(
            modifier = Modifier
                .width(4.dp) // 设置边框宽度
                .fillMaxHeight()
                .background(Purple3, shape = RoundedCornerShape(topStart = 4.dp, bottomStart = 4.dp))
                .padding(end = 10.dp)
        )
        Image(
            painter = painterResource(id = R.drawable.info),
            contentDescription = stringResource(id = R.string.long_press_an_item),
        )
        Text(
            text = stringResource(id = R.string.long_press_an_item),
            fontFamily = FontFamily(Font(R.font.inter_medium)),
            fontSize = 12.sp,
            color = Gray5,
            modifier = Modifier.padding(horizontal = 10.dp)
        )
    }
}

说明:

  • 把 borderWidth 换成你需要的数值即可调整边框粗细
  • 背景色根据你的UI需求替换,避免边框和内容重叠
  • 圆角参数要和原布局的 RoundedCornerShape 保持一致,确保视觉统一

内容的提问来源于stack exchange,提问作者Chup bae

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:50:29