Botão·Grátis
Botão de excluir com confirmação (Compose)
Botão de excluir do Material 3 que pergunta antes. Ao tocar, ele abre uma caixa de diálogo, e onConfirm só roda quando o usuário toca em Delete nela. A pergunta continua aberta depois de girar o aparelho. Se a sua exclusão puder ser desfeita, troque o texto do aviso.
Instalação grátis.
Se o PocketCode estiver instalado no seu Android, isto abre a página no app.
Prévia
ConfirmDeleteButton.kt · 73 linhas
// Delete button for Jetpack Compose and Material 3 that asks before it acts.
// Tapping it opens a dialog; onConfirm only runs when the user taps "Delete" in that dialog.
// The question survives rotation (rememberSaveable), and tapping outside or "Cancel" closes it.
//
// ConfirmDeleteButton(itemName = "Invoice 2041", onConfirm = { viewModel.delete(invoice.id) })
//
// If your delete can be undone (a trash, an undo snackbar), change `warning` so it says so.
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun ConfirmDeleteButton(
itemName: String,
onConfirm: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
label: String = "Delete",
warning: String = "This can't be undone.",
) {
var asking by rememberSaveable { mutableStateOf(false) }
val error = MaterialTheme.colorScheme.error
OutlinedButton(
onClick = { asking = true },
enabled = enabled,
modifier = modifier.heightIn(min = 48.dp),
colors = ButtonDefaults.outlinedButtonColors(contentColor = error),
border = BorderStroke(
width = 1.dp,
color = if (enabled) error else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f),
),
) {
Text(label)
}
if (asking) {
AlertDialog(
onDismissRequest = { asking = false },
title = { Text("Delete $itemName?") },
text = { Text(warning) },
confirmButton = {
TextButton(
onClick = {
asking = false
onConfirm()
},
colors = ButtonDefaults.textButtonColors(contentColor = error),
) {
Text("Delete")
}
},
dismissButton = {
TextButton(onClick = { asking = false }) {
Text("Cancel")
}
},
)
}
}Mudanças na 1.0.0
Primeira versão.