What is the easiest way in Kotlin to show Android ProgressBar covering the whole app untill some code is finished (for example adding some data to database)?
The ProgressBar can be shown using this snippet:
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please Wait")
progressDialog.setMessage("Loading ...")
progressDialog.show()
But how can I easily make it visible until the task is done?
CodePudding user response:
Ok, I figured it out!
First of all, declare the ProgressBar this way at the top of any class:
lateinit var progressDialog: ProgressDialog
Then, start it this way:
progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please Wait")
progressDialog.setMessage("Loading ...")
progressDialog.setCancelable(false) // blocks UI interaction
progressDialog.show()
The above code will block UI until your code completes. When it finishes, just hide the progressBar:
progressDialog.hide()
Simple, neat and fine! Enjoy! :-)
CodePudding user response:
if you are use jetpack compose;
class MainActivity : ComponentActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
yourTheme{
MainScreenView()
}
}
}
@Composable
fun MainScreenView(){
var isLoading by remember {
mutableStateOf(yourViewModel.isLoading.value)
}
if(isLoading){
//Loading View
}else{
//Your Actual View
}
}
class YourViewModel (
private val useCases: UseCases
): ViewModel() {
var isLoading = mutableStateOf(false)
private set
fun exampleAddDataToDatabase(data: Data){
viewModelScope.launch {
useCases.addDataToDatabase(data).collect{ response ->
when(response){
is Response.Loading -> {isLoading.value = true}
is Response.Success -> {isLoading.value = false}
is Response.Error -> {}
}
}
}
}
}