Jetpack Compose - Alert dialog

Dialogs provide important prompts in a user flow. They can require an action, communicate information, or help users accomplish a task.

This example demonstrates how to make a default alert dialog in android jet compose.



package
com.compose.example

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.*
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 com.compose.example.ui.theme.ComposeExampleTheme

class MainActivity : ComponentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeExampleTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainContent()
}
}
}
}
}


@Composable
fun MainContent() {
val openDialog = remember { mutableStateOf(false) }
Box(
contentAlignment = Alignment.Center
) {
// * Alert dialog Sample
Button(
onClick = {
openDialog.value=true
},
modifier = Modifier.align(Alignment.Center)
) {
Text(text = "Alert Dialog Sample")
}
}

//Alert Dialog Sample
if (openDialog.value) {
AlertDialog(
onDismissRequest = {
// Dismiss the dialog when the user clicks outside the dialog or on the back
// button. If you want to disable that functionality, simply use an empty
// onDismissRequest.
openDialog.value = false
},
title = {
Text(text = "Title")
},
text = {
Text(text = "Turned on by default")
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Dismiss")
}
}
)
}
}



..

Read More

Comments