Monday, March 8, 2021

jetpack compose - Indeterminate CircularProgressIndicator

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
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.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val isVisible = remember { mutableStateOf(false) }
        val isEnable = remember { mutableStateOf(true) }
        val result = remember { mutableStateOf("") }

        val handler = Handler(Looper.getMainLooper())

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Button(
                onClick = {
                    isVisible.value = true
                    isEnable.value = false
                    result.value = "Task running...."

                    Thread {
                        Thread.sleep(8 * 1000)

                        handler.post {
                            isVisible.value = false
                            result.value = "Task finished."
                            isEnable.value = true
                        }
                    }.start()
                },
                enabled = isEnable.value
            ) {
                Text(text = "Do Task")
            }

            if (isVisible.value){
                Row(
                    modifier = Modifier.padding(top = 16.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(25.dp)
                ) {
                    CircularProgressIndicator()
                    CircularProgressIndicator(
                        color = Color(0xFFE30022)
                    )
                }
            }

            Spacer(modifier = Modifier.requiredHeight(16.dp))
            Text(
                text = result.value,
                fontSize = 20.sp
            )
        }
    }


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