Android ProgressBar Kotlin - 显示直到某些代码完成

Android ProgressBar Kotlin - show until some code is completed

在 Kotlin 中 显示 Android ProgressBar 覆盖整个应用程序直到完成某些代码(例如将一些数据添加到数据库)的最简单方法是什么?

可以使用以下代码片段显示 ProgressBar:

val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please Wait")
progressDialog.setMessage("Loading ...")
progressDialog.show()

但是在任务完成之前,我怎样才能轻松地使其可见?

如果您使用的是 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 -> {}
                }
            }
        }
    }
}

好的,我明白了!

首先,在任何 class:

的顶部以这种方式声明 ProgressBar
lateinit var progressDialog: ProgressDialog

那么,就这样开始吧:

progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please Wait")
progressDialog.setMessage("Loading ...")
progressDialog.setCancelable(false) // blocks UI interaction 
progressDialog.show()

以上代码将阻塞 UI,直到您的代码完成。完成后,只需隐藏进度条:

progressDialog.hide()

简洁大方!享受! :-)