Skip to content

Instantly share code, notes, and snippets.

@kikin81
Last active January 27, 2023 23:05
Show Gist options
  • Save kikin81/ef5c4f8cd09937cffe4dc13ea0b8b13d to your computer and use it in GitHub Desktop.
Save kikin81/ef5c4f8cd09937cffe4dc13ea0b8b13d to your computer and use it in GitHub Desktop.
Compose Loading button
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun LoadingButton(
text: String,
enabled: Boolean = true,
loading: Boolean = false,
clickHandler: () -> Unit,
) {
Button(
enabled = enabled && loading.not(),
onClick = clickHandler,
shape = RoundedCornerShape(size = 8.dp),
modifier = Modifier.defaultMinSize(minWidth = 42.dp),
) {
Text(
text = if (loading) "Loading" else text,
)
}
}
@Preview
@Composable
fun ButtonPreview() {
var isEnabled by remember {
mutableStateOf(true)
}
var isLoading by remember {
mutableStateOf(false)
}
Column {
LoadingButton(
text = "Next",
enabled = isEnabled,
loading = isLoading,
) {
}
SwitchLabel(
checked = isEnabled,
onCheckedChanged = { isEnabled = !isEnabled },
label = "Enabled",
)
SwitchLabel(
checked = isLoading,
onCheckedChanged = { isLoading = !isLoading },
label = "Loading",
)
}
}
@Composable
fun SwitchLabel(
checked: Boolean,
onCheckedChanged: ((Boolean) -> Unit),
label: String,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Switch(checked = checked, onCheckedChange = onCheckedChanged)
Spacer(modifier = Modifier.padding(8.dp))
Text(text = label)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment