【问题标题】:Any way to wait for the value from MaterialAlertDialogBuilder? Android - Kotlin有什么方法可以等待来自 MaterialAlertDialogBu​​ilder 的值?安卓 - 科特林
【发布时间】:2023-03-31 08:42:01
【问题描述】:

我知道我可以从使用对话框中用户输入的 MaterialAlertDialogBu​​ilder 内部调用函数,但我想知道是否有一种方法(最好是一种好的做法)来等待用户输入值和应用程序执行后续代码。我尝试使用 async .await() 和 kotlin-coroutines 但没有弄明白。

这是 MaterialAlertDialogBu​​ilder 实现的示例。

val nameInputDialog = MaterialAlertDialogBuilder(requireContext())
val customAlertDialogView = LayoutInflater.from(requireContext())
            .inflate(R.layout.dialod_input_et, null, false)
val inputNameDialog: EditText = customAlertDialogView.findViewById(R.id.input_dialog_et)
nameInputDialog.setView(customAlertDialogView)
            .setTitle("Type the name")
            .setPositiveButton("Accept") { dialog, _ ->
                val nameToInput = inputNameDialog.text.toString()

                if (nameToInput == "") {
                    Toast.makeText(requireContext(), "Type a name", Toast.LENGTH_SHORT)
                        .show()
                    makeDialogBoxAndSetGroupID()
                } else if (nameToInput != "") {
                    GlobalScope.launch() {
                        nameToDisplay = async {
                            nameToInput
                        }
                    }
                    dialog.dismiss()
                }
            }
            .setNegativeButton("Cancel") { dialog, _ ->
                dialog.dismiss()
            }.show()

【问题讨论】:

  • 信息不足。请通过代码示例说明您要暂停的内容。
  • @rupinderjeet 这是我的对话框实现的更新问题
  • 您究竟需要等待什么?

标签: android kotlin dialog kotlin-coroutines


【解决方案1】:

您究竟需要等待什么?

如果您有一个带有 EditText 的对话框,并且您希望确保对话框保持打开状态,直到用户键入您认为有效的内容,那么您需要委托所有这些验证,保留对您的对话框的引用,并采取相应的行动一旦您的 ViewModel 响应。

简而言之。

Fragment/Activity:创建一个对话框并保存一个引用。

val nameInputDialog =  ... show()

onPositiveButton里面:

val nameToInput = inputNameDialog.text.toString()
viewModel.inputNameChanged(nameToInput)

在您的视图模型中:

fun inputNameChanged(name: String) {
    //validate (preferably delegate to a validator/useCase so you can UT it)

    if (validator.isValid(name)) {
      _uiState.postValue(YourSealedClass.Valid(name)) 
    } else {
       _uiState.postValue(YourSealedClass.Empty())//for e.g.
    }
}

然后回到你观察到这个的片段/活动中......

viewModel.uiState.observe(viewLifecycleOwner, Observer { state ->
   when(state) {
     is YourSealedClass.Valid -> dialog.dismiss() 
     is YourSealedClass.Empty -> {
         Toast.makeText(...).show() //a toast is bad for this, but it works.
     }
}

这是how Google recommends,你以“被动”的方式工作。

【讨论】:

  • 不是我一直在寻找使用观察者购买的答案似乎是更好的方法。
猜你喜欢
  • 1970-01-01
  • 2019-10-17
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2021-07-10
相关资源
最近更新 更多