Sunday, March 7, 2021

jetpack compose - How to use AlertDialog

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val openDialog = remember { mutableStateOf(false)}
        val backgroundColor = remember {
            mutableStateOf(Color(0xFFF5F5F5))
        }

        Column(
            Modifier
                .background(backgroundColor.value)
                .fillMaxSize()
        ) {
            Button(onClick = {
                    openDialog.value = true
                },
                modifier = Modifier.padding(16.dp)
            ) {
                Text(text = "Show Dialog")
            }

            if (openDialog.value){
                AlertDialog(
                    onDismissRequest = { openDialog.value = false },
                    title = { Text(text = "Change background color") },
                    text = { Text(
                        text = "Do you want to apply yellow background?"
                    ) },
                    
                    confirmButton = {
                        Button(onClick = {
                                openDialog.value = false
                                backgroundColor.value = Color(0xFFFFD300)
                            }) {
                                Text(text = "Yes")
                        }
                    },
                    
                    dismissButton = {
                        Button(onClick = { 
                                openDialog.value = false
                            },
                            colors = ButtonDefaults.buttonColors(
                                backgroundColor = Color.Red,
                                contentColor = Color.White
                            )
                            ) {
                                Text(text = "Cancel")
                        }
                    }
                )
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}