Android Jetpack

Create AlertDialog with Jetpack Compose

Pinterest LinkedIn Tumblr

If you’re looking to create interactive alert dialogs with Jetpack Compose. Creating a custom alert dialog is fast, straightforward, and hassle-free dialog Jetpack Compose. So let’s start how to build a fully-functioning custom alert dialog by following these steps.

Installing and Setting Up Jetpack Compose

Before you dive in, you need to first install Jetpack Compose and set it up for your project. To do this, you’ll need to add the Jetpack Compose tools to your app-level build.gradle file. Or you can create an empty compose android project.

 implementation "androidx.compose.ui:ui:$compose_ui_version"
 implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"

Creating a normal dialog jetpack

To create a user-friendly Dialog, start by defining the structure of your Dialog. A typical DialogBox consists of a title, a message, and one confirms action button. This type of alert dialog will display some information to the user. Once the user taps on confirm button then it will disappear

package com.compose.customalertdialogjetpackcompose

import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

@Composable
fun PopupDialog(onDismiss: () -> Unit, onConfirm: () -> Unit) {
  androidx.compose.material.AlertDialog(onDismissRequest = onDismiss, title = {
    Text(
      text = "Update title here", modifier = Modifier.padding(4.dp), fontWeight = FontWeight.Bold
    )
  }, text = {
    Text(text = "Update message here", modifier = Modifier.padding(4.dp))
  }, confirmButton = {
    Button(onClick = {
      /**
       * invoke onConfirm
       */
      onConfirm.invoke()
    }) {
      Text(text = "Ok")
    }
  }, dismissButton = {})
}

Implementing Interactions with AlertDialog: Button Actions, Dismissal

To ensure users can interact and engage with your dialog box, you’ll need to add support for button actions. This means writing code that specifies what each action does when tapped or selected.

package com.compose.customalertdialogjetpackcompose

import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

@Composable
fun AlertDialog(onDismiss: () -> Unit, onConfirm: () -> Unit) {
  androidx.compose.material.AlertDialog(onDismissRequest = onDismiss, title = {
    Text(text = "Request Failed", modifier = Modifier.padding(4.dp), fontWeight = FontWeight.Bold)
  }, text = {
    Text(
      text = "We encounter some issue in APIs, Please try again", modifier = Modifier.padding(4.dp)
    )
  }, confirmButton = {
    //
    Button(onClick = {
      onConfirm.invoke()
    }) {
      /**
       * invoke onConfirm pass any param if needed
       */
      Text(text = "Retry")
    }
  }, dismissButton = {
    /**
     * invoke onDismiss button
     */
    Button(onClick = onDismiss) {
      Text(text = "Cancel")
    }
  })
}

Customizing the Jetpack Compose AlertDialog

It’s not enough to just add action buttons, you also want to be able to customize the look and feel of your alert dialog. This includes setting text fonts and colors as well as defining background elements such as fill, border, and corner radius.

What you can customize

The following param you can customize in Alert Dialog, Based on your own need you can utilize

    • onDismissRequest – Executes when the user tries to dismiss the Dialog by clicking outside or pressing the back button. This is not called when the dismiss button is clicked.
    • confirmButton – A button which is meant to confirm a proposed action, thus resolving what triggered the dialog. The dialog does not set up any events for this button so they need to be set up by the caller.
    • modifier – Modifier to be applied to the layout of the dialog.
    • dismissButton – A button which is meant to dismiss the dialog. The dialog does not set up any events for this button so they need to be set up by the caller.
    • title – The title of the Dialog should specify the purpose of the Dialog. The title is not mandatory, because there may be sufficient information inside the text. Provided text style will be Typography.subtitle1.
    • text – The text which presents the details regarding the Dialog’s purpose. Provided text style will be Typography.body2.
    • shape – Defines the Dialog’s shape
    • backgroundColor – The background color of the dialog.
    • contentColor – The preferred content color provided by this dialog to its children.
    • properties – Typically platform specific properties to further configure the dialog.

    Let’s create Custom Alert Dialog

    package com.compose.customalertdialogjetpackcompose
    
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.height
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material.AlertDialog
    import androidx.compose.material.Button
    import androidx.compose.material.Text
    import androidx.compose.material.TextField
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.text.font.FontWeight
    import androidx.compose.ui.text.input.TextFieldValue
    import androidx.compose.ui.unit.dp
    
    @Composable
    fun CustomAlertDialog(onDismiss: () -> Unit, onConfirm: (name: String) -> Unit) {
      val name = remember { mutableStateOf(TextFieldValue("")) }
      AlertDialog(onDismissRequest = onDismiss, title = {
        Text(
          text = "Enter your name",
          modifier = Modifier
            .padding(4.dp)
            .height(48.dp),
          fontWeight = FontWeight.Bold
        )
      }, text = {
        Column(modifier = Modifier.fillMaxWidth()) {
          TextField(
            value = name.value,
            onValueChange = { name.value = it },
            label = { Text(text = "Your name") },
            placeholder = { Text(text = "Surya") },
            modifier = Modifier.padding(4.dp)
          )
        }
      }, confirmButton = {
        Button(onClick = {
          val input = name.value.text
          if (input.isNotEmpty()) onConfirm.invoke(input)
        }) {
          Text(text = "Add")
        }
      }, dismissButton = {
        Button(onClick = onDismiss) {
          Text(text = "Cancel")
        }
      })
    }

    How to use above composable component

    Let’s open the MainActivity, here I am creating a @Composable function named AlertDialogPlayground, I this playground I will call all types of dialog

    @Composable
    fun AlertDialogPlayground() {
      val showPopupDialog = remember { mutableStateOf(false) }
      val showAlertDialog = remember { mutableStateOf(false) }
      val showCustomDialog = remember { mutableStateOf(false) }
      val nameList = remember { mutableStateOf("") }
      Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
      ) {
        /**
         * Button for display popup alert dialog
         */
        Button(
          onClick = {
            showPopupDialog.value = true
          }, modifier = Modifier
            .padding(8.dp)
            .width(200.dp)
        ) {
          Text(text = "Show PopupDialog")
        }
        if (showPopupDialog.value) {
          PopupDialog(onDismiss = { showPopupDialog.value = false }, onConfirm = {
            showPopupDialog.value = false
          })
        }
        /**
         * Button for display alert dialog
         */
        Button(
          onClick = {
            showAlertDialog.value = true
          }, modifier = Modifier
            .padding(8.dp)
            .width(200.dp)
        ) {
          Text(text = "Show AlertDialog")
        }
        if (showAlertDialog.value) {
          AlertDialog(onDismiss = { showAlertDialog.value = false }, onConfirm = {
            showAlertDialog.value = false
          })
        }
    
        /**
         * Button for display  Custom alert dialog
         */
        Button(
          onClick = {
            showCustomDialog.value = true
          }, modifier = Modifier
            .padding(8.dp)
            .width(200.dp)
        ) {
          Text(text = "Show  CustomDialog")
        }
        if (showCustomDialog.value) {
          CustomAlertDialog(onDismiss = { showCustomDialog.value = false }, onConfirm = { name ->
            nameList.value = nameList.value + "\n" + name
            showCustomDialog.value = false
          })
        }
    
        Text(
          text = "List\n" + "----------------------------------------------------------------------------------" + nameList.value,
          modifier = Modifier
            .padding(8.dp)
            .fillMaxWidth()
            .padding(16.dp),
          fontWeight = FontWeight.Normal
        )
      }
    }
    
    

    Finalizing, Call the function composable Surface

    package com.compose.customalertdialogjetpackcompose
    
    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.compose.foundation.layout.*
    import androidx.compose.material.Button
    import androidx.compose.material.MaterialTheme
    import androidx.compose.material.Surface
    import androidx.compose.material.Text
    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.text.font.FontWeight
    import androidx.compose.ui.unit.dp
    import com.compose.customalertdialogjetpackcompose.ui.theme.CustomAlertDialogJetpackComposeTheme
    
    class MainActivity : ComponentActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
          CustomAlertDialogJetpackComposeTheme {
            // A surface container using the 'background' color from the theme
            Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
              AlertDialogPlayground()
            }
          }
        }
      }
    }

    Conclusion

    In this tutorial, we have learned how you can create different types of interactive Jetpack Compose AlertDialog. I hope this post will help you. If you have any queries feel free to reach out using the comment box. I will happy to take your queries. Read our other post on Jetpack Compose.

    Write A Comment