kotlin 在compose android中创建一个圆形按钮并将文本居中

4c8rllxm  于 2023-03-19  发布在  Kotlin
关注(0)|答案(3)|浏览(275)

我正在尝试创建一个圆形按钮,其中一些首字母的文本应该居中。按钮大小应该是34.dp,文本应该是13.sp,但我必须增加按钮的大小才能使文本正确显示
我认为文本不显示的原因是因为文本合成的内部填充。

Button(
    modifier = Modifier.size(49.dp),
    colors = ButtonDefaults.buttonColors(
        containerColor = Color.Black,
        contentColor = Color.White),
    onClick = {

    }) {
    Text(text = "JB",
        fontSize = 13.sp,
        fontWeight = FontWeight.SemiBold,
        style = TextStyle(
            lineHeightStyle = LineHeightStyle(
                alignment = LineHeightStyle.Alignment.Center,
                trim = LineHeightStyle.Trim.Both
            )
        )
    )
}
uajslkp6

uajslkp61#

如果要使用34.dp作为大小,则必须应用0.dpcontentPadding

Button(
        modifier = Modifier.size(34.dp),
        shape = CircleShape,
        contentPadding = PaddingValues(0.dp),
        //...

wgeznvg7

wgeznvg72#

设置默认内容填充contentPadding = PaddingValues(0.dp)

ElevatedButton(
onClick = {
    Toast.makeText(this@MainActivity, "Click", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.width(34.dp),
contentPadding = PaddingValues(0.dp)
) {
    Text(
        text = "JB",
        fontSize = 13.sp,
        fontWeight = FontWeight.SemiBold,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis
    )
}
ar7v8xwq

ar7v8xwq3#

请添加形状属性按钮如下,也添加内容填充为0以及。

Button(onClick = { /*TODO*/ },
        modifier= Modifier.size(34.dp),  
        shape = CircleShape,
        contentPadding = PaddingValues(0.dp),  
        colors = ButtonDefaults.buttonColors(contentColor =  Color.White)
    ) {
        Text(text = "JB",
            fontSize = 13.sp,
            fontWeight = FontWeight.SemiBold,
            style = TextStyle(
                lineHeightStyle = LineHeightStyle(
                    alignment = LineHeightStyle.Alignment.Center,
                    trim = LineHeightStyle.Trim.Both
                )
            )
        )
    }

相关问题