跳转到内容
按钮·免费

主按钮(Compose)

点按时会轻微振动的 Material 3 按钮。设置 loading = true 后会显示加载圈,并在请求进行中忽略点按。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

PrimaryButton.kt · 52 行
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp

/**
 * Material 3 primary button that vibrates briefly on tap.
 *
 * While [loading] is true it shows a small spinner and ignores taps, so a form can't be sent twice.
 * Only needs androidx.compose.material3.
 *
 * PrimaryButton(text = "Save", onClick = viewModel::save, loading = state.saving)
 */
@Composable
fun PrimaryButton(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    loading: Boolean = false,
) {
    val haptics = LocalHapticFeedback.current
    Button(
        onClick = {
            // LongPress works on every Compose version; with Compose UI 1.8+ you can use Confirm.
            haptics.performHapticFeedback(HapticFeedbackType.LongPress)
            onClick()
        },
        // 48 dp is the minimum touch target in the Material guidelines.
        modifier = modifier.heightIn(min = 48.dp),
        enabled = enabled && !loading,
    ) {
        if (loading) {
            CircularProgressIndicator(
                modifier = Modifier.size(18.dp),
                color = LocalContentColor.current,
                strokeWidth = 2.dp,
            )
            Spacer(Modifier.width(8.dp))
        }
        Text(text)
    }
}

1.0.0 的变更

首个版本。

相关