创建带有轮廓 Jetpack Compose 的芯片

时间:2021-02-21 11:50:23

标签: android-jetpack-compose

我有以下可组合函数来构建芯片:

@Composable
fun CategoryChip(
  category: String,
  isSelected: Boolean = false,
  onSelectedCategoryChanged: (String) -> Unit,
  onExecuteSearch: () -> Unit
) {
  Surface(
    modifier = Modifier.padding(end = 8.dp, bottom = 8.dp),
    elevation = 8.dp,
    shape = RoundedCornerShape(16.dp),
    color = when {
      isSelected -> colorResource(R.color.teal_200)
      else -> colorResource(R.color.purple_500)
    }
  ) {
    Row(modifier = Modifier
      .toggleable(
        value = isSelected,
        onValueChange = {
          onSelectedCategoryChanged(category)
          onExecuteSearch()
        }
      )) {
      Text(
        text = category,
        style = MaterialTheme.typography.body2,
        color = Color.White,
        modifier = Modifier.padding(8.dp)
      )
    }
  }
}

这将创建以下芯片:

enter image description here

但我想要实现的是以下内容:

enter image description here

是否可以使用 Jetpack Compose 创建这样的形状?

2 个答案:

答案 0 :(得分:2)

是的,您所要做的就是在表面上添加边框。

Surface(
    modifier = Modifier.padding(end = 8.dp, bottom = 8.dp),
    elevation = 8.dp,
    shape = RoundedCornerShape(16.dp),
    border = BorderStroke(
        width = 1.dp,
        color = when {
            isSelected -> colorResource(R.color.teal_200)
            else -> colorResource(R.color.purple_500)
        }
     )
)

答案 1 :(得分:1)

以 Code Poet 的回答为基础,我想展示如何制作带有背景颜色的 Material Chip:

@Composable
fun buildChip(label: String, icon: ImageVector? = null) {
    Box(modifier = Modifier.padding(8.dp)) {
        Surface(
            elevation = 1.dp,
            shape = MaterialTheme.shapes.small,
            color = Color.LightGray
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                if (icon != null) Icon(
                    icon,
                    modifier = Modifier
                        .fillMaxHeight()
                        .padding(horizontal = 4.dp)
                )
                Text(
                    label,
                    modifier = Modifier.padding(8.dp),
                    style = MaterialTheme.typography.button.copy(color = Color.DarkGray)
                )
            }
        }
    }
}