Android jetpack compose show AlertDialog on Button Click

Here is a complete example of showing an AlertDialog with JetPack Compose.

When a button is clicked an AlertDialog will be shown. AlertButton is the custom composable button, it manages a local boolean state to control if it should show the AlertDialog. When this button is clicked, it will update the this boolean to true, when this boolean becomes true, it will render the AlertDialog. When AlertDialog is dismissed, this boolean will be set to false which in turn cause the AlertDialog not to be rendered afterwards.

alert is another custom composable which is the actual AlertDialog.

AlertButtonPreview is a composable annotated with Preview to show the preview of the AlertButton in Android Studio.

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.codelab.basics.ui.BasicsCodelabTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                AlertButton()
            }
        }
    }
}

@Composable
private fun AlertButton() {
    val showDialog = remember { mutableStateOf(false) }
    if (showDialog.value) {
        alert(msg = "Hello, this is an alert dialog!",
            showDialog = showDialog.value,
            onDismiss = {showDialog.value = false})
    }
    Surface {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("Click the button to show an alert!")
            Button(
                modifier = Modifier.padding(vertical = 24.dp),
                onClick = {showDialog.value = true}
            ) {
                Text("Click")
            }
        }
    }
}

@Composable
fun alert(msg : String,
          showDialog: Boolean,
          onDismiss: () -> Unit) {
    if (showDialog) {
        AlertDialog(
            title = {
                Text(msg)
            },
            onDismissRequest = onDismiss,
            confirmButton = {
                TextButton(onClick = onDismiss ) {
                    Text("Dismiss")
                }
            },
            dismissButton = {}
        )
    }
}

@Preview(showBackground = true, widthDp = 320, heightDp = 320)
@Composable
fun AlertButtonPreview() {
    BasicsCodelabTheme {
        AlertButton()
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search