如何将 CircularProgressIndicator 在按钮中垂直居中?

问题描述 投票:0回答:1

我想创建一个

Button
,在禁用时显示
CircularProgressIndicator
(用例:用户单击按钮,发出网络请求,在此期间按钮被禁用,并显示一个漂亮的微调器)。我遇到的问题是
CircularProgressIndicator
没有垂直居中。这是我当前的代码:

@Preview
@Composable
private fun ButtonSandbox() {
    Button(
        enabled = false,
        modifier = Modifier.fillMaxWidth()
            .height(48.dp),
        onClick = {},
        colors = ButtonDefaults.buttonColors(
            disabledContainerColor = MaterialTheme.colorScheme.primary,
            disabledContentColor = MaterialTheme.colorScheme.onPrimary
        )
    ) {
        CircularProgressIndicator(
            color = MaterialTheme.colorScheme.onPrimary,
            trackColor = MaterialTheme.colorScheme.onPrimary, // just to make it completely visible in preview
            modifier = Modifier.align(Alignment.CenterVertically) // my (failed) attempt to fix it
        )
    }
}

这就是它的样子,请注意

CircularProgressIndicator
不是垂直居中的:

我该如何解决这个问题?

android button android-jetpack-compose spinner
1个回答
0
投票

Button 使用一个 Surface 和一个 Row 来显示内容。如果你看看默认的最小高度是 58.dp。所以这应该有效

@Preview
@Composable
fun ButtonSandbox() {
    Button(
        enabled = false,
        modifier = Modifier.fillMaxWidth()
            .height(58.dp),
        onClick = {},
        colors = ButtonDefaults.buttonColors(
            disabledContainerColor = MaterialTheme.colorScheme.primary,
            disabledContentColor = MaterialTheme.colorScheme.onPrimary
        )
    ) {
        CircularProgressIndicator(
            color = MaterialTheme.colorScheme.onPrimary,
            trackColor = MaterialTheme.colorScheme.onPrimary, // just to make it completely visible in preview
        )
    }
}

如果您想自定义按钮高度,我建议您使用 Surface 和行并根据需要提供高度。

© www.soinside.com 2019 - 2024. All rights reserved.