在我的Android应用中,我有一个观察者,在回调中,我想显示一个AlertDialog。但是,Builder方法需要上下文。我需要获取该片段所在的活动的上下文,但不确定如何获取它:
viewModel.onError.observe(this, Observer {
val mAlertDialog = AlertDialog.Builder(activity) // This needs the activity's context
mAlertDialog.setMessage(it.toString())
mAlertDialog.show()
})
答案 0 :(得分:1)
您应该通过 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()
答案 1 :(得分:0)
viewModel.onError.observe(this, Observer {
val mAlertDialog = AlertDialog.Builder(this@LoginActivity)
mAlertDialog.setMessage(it.toString())
mAlertDialog.show()
})