在 Kotlin 的适配器中调用时如何在 AlertDialog.Builder() 中设置上下文?
How to set Context in AlertDialog.Builder() when called in an Adapter in Kotlin?
我是 Kotlin 新手。当按下属于 RecyclerView 的按钮时,我正在尝试使用 AlertDialog 框。 RecylerView适配器在MainActivity中调用。
下面是我在适配器中的代码。使用 'this' 作为 AlertDialog.Builder(this) 的上下文会带来错误,因为我需要提供上下文,但 'this' 被识别为适配器。我尝试了很多方法都没有成功。
如何正确设置上下文?
class contactAdapter (val contacts: ArrayList<Contact>, val contactClick: (Contact) -> Unit) : RecyclerView.Adapter<contactAdapter.Viewholder>() {.......
fun reminderButtonClicked (view:View){
reminderAlertDialog() // call the dialogbox when this button is pressed in the recyclerview
}
fun reminderAlertDialog(){
val dialog = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.reminder_alert_dialog,null)
dialog.setView(dialogView)
dialog.setCancelable(true)
val myAlertDialog = dialog.show()
....
}
视图引用了 Context
,因此以下内容应该有效:
fun reminderButtonClicked(view: View) {
reminderAlertDialog(view.context)
}
fun reminderAlertDialog(context: Context) {
val dialog = AlertDialog.Builder(context)
...
}
我是 Kotlin 新手。当按下属于 RecyclerView 的按钮时,我正在尝试使用 AlertDialog 框。 RecylerView适配器在MainActivity中调用。
下面是我在适配器中的代码。使用 'this' 作为 AlertDialog.Builder(this) 的上下文会带来错误,因为我需要提供上下文,但 'this' 被识别为适配器。我尝试了很多方法都没有成功。
如何正确设置上下文?
class contactAdapter (val contacts: ArrayList<Contact>, val contactClick: (Contact) -> Unit) : RecyclerView.Adapter<contactAdapter.Viewholder>() {.......
fun reminderButtonClicked (view:View){
reminderAlertDialog() // call the dialogbox when this button is pressed in the recyclerview
}
fun reminderAlertDialog(){
val dialog = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.reminder_alert_dialog,null)
dialog.setView(dialogView)
dialog.setCancelable(true)
val myAlertDialog = dialog.show()
....
}
视图引用了 Context
,因此以下内容应该有效:
fun reminderButtonClicked(view: View) {
reminderAlertDialog(view.context)
}
fun reminderAlertDialog(context: Context) {
val dialog = AlertDialog.Builder(context)
...
}