Skip to content
Button·Free

Primary button (Compose)

Material 3 button that vibrates briefly on tap. Set loading = true and it shows a spinner and ignores taps while a request runs.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

PrimaryButton.kt · 52 lines
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)
    }
}

Changes in 1.0.0

First version.

Related