Android MVVM架构中,Dialog视图需要与ViewModel交互来实现逻辑。以下是基于MVVM架构实现Dialog的示例代码:
在ViewModel中,您可以声明以下属性以控制Dialog的显示:
private var _dialogMessage = MutableLiveData()
val dialogMessage: LiveData
get() = _dialogMessage
private var _dialogTitle = MutableLiveData()
val dialogTitle: LiveData
get() = _dialogTitle
private var _isDialogShown = MutableLiveData()
val isDialogShown: LiveData
get() = _isDialogShown
接下来,您需要在ViewModel中实现Dialog的逻辑,在特定条件下显示它:
fun showDialog(title: String, message: String) {
_dialogTitle.value = title
_dialogMessage.value = message
_isDialogShown.value = true
}
fun hideDialog() {
_isDialogShown.value = false
}
要在视图中使用它,请在XML布局中将以下代码放在Dialog的根视图中:
关于Dialog布局,您可以按照以下方式定义它:
在代码中,您还需要编写适配器类(DialogViewAdapter)以在视图和ViewModel之间进行通信:
class DialogViewAdapter {
companion object {
@BindingAdapter("dialogTitle")
@JvmStatic
fun setDialogTitle(view: AlertDialog, title: String