Jetpack Compose Show Progress Bar Dialog

December 15, 2021
@Composable
fun SelectPhotoScreen() {
    var showProgress by remember { mutableStateOf(false) }
    var progressState by remember { mutableStateOf( Pair(0.0f, "") ) }

    fun onStart() {
        showProgress = true

        coroutineScope.launch {
            progressState = Pair(0.0f, "Starting")
            delay(1000)
            progressState = Pair(0.1f, "Going well")
            delay(2000)
            progressState = Pair(0.1f, "Half way through")
            delay(2000)
            progressState = Pair(0.1f, "Done")
            // delay(1000)
            // showProgress = false
        }
    }


    Button(onClick = { onStart() }) {
      Text("Start")
    }


    if (showProgress) {
        ProgressDialog(
            title = "Importing ...",
            progressState = progressState,
            onDismiss = { showProgress = false },
            onComplete = {
                // do something
                showProgress = false
            }
        )
    }
}
@Composable
fun ProgressDialog(
    title: String? = null,
    progressState: Pair<Float, String>,
    onDismiss: () -> Unit,
    onComplete: () -> Unit) {
    AlertDialog(
        modifier = Modifier.fillMaxWidth(),
        onDismissRequest = {
            onDismiss()
        },
        /*
        // https://stackoverflow.com/questions/69452854/increase-space-between-title-and-text-of-alertdialog-in-compose
        title = {
           if (!title.isNullOrEmpty()) {
               Text(title)
           }
        },
         */
        text = {
            Column (
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                // horizontalAlignment = Alignment.CenterHorizontally
            ) {
                if (!title.isNullOrEmpty()) {
                    Text(title,
                        modifier = Modifier.padding(vertical = 8.dp),
                        style = MaterialTheme.typography.subtitle1)
                }


                val (progress, message) = progressState


                ProgressBar(modifier = Modifier
                    .height(16.dp)
                    .fillMaxWidth(), progress = progress)
    
                if (message.isNotEmpty()) {
                  Text(modifier = Modifier.padding(vertical = 8.dp), text = message)
                }
            }
        },
        // buttons = { }
        dismissButton = {
            val isComplete = progressState.status != Status.LOADING
            Button(enabled = isComplete, onClick = onComplete ) {
                Text("Done")
            }
        },
        confirmButton = {

        }
    )
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.