gpt4 book ai didi

android - 使用 Kotlin 在 fragment 中创建 AlertDialog

转载 作者:行者123 更新时间:2023-11-29 23:08:33 32 4
gpt4 key购买 nike

在我的 Android 应用程序中,我有一个观察者,在回调中我想显示一个 AlertDialog。然而,Builder 方法需要一个上下文。我需要获取 fragment 所在 Activity 的上下文,但不确定如何获取它:

viewModel.onError.observe(this, Observer {
val mAlertDialog = AlertDialog.Builder(activity) // This needs the activity's context
mAlertDialog.setMessage(it.toString())
mAlertDialog.show()
})

最佳答案

您应该为 Fragment 传递 activity!!

val dialogBuilder = AlertDialog.Builder(activity!!)
dialogBuilder.setMessage(it.toString())
// if the dialog is cancelable
.setCancelable(false)
.setPositiveButton("Ok", DialogInterface.OnClickListener {
dialog, id ->
dialog.dismiss()

})

val alert = dialogBuilder.create()
alert.setTitle("Test")
alert.show()

关于android - 使用 Kotlin 在 fragment 中创建 AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56287917/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com