【发布时间】:2020-08-25 14:48:20
【问题描述】:
我是 Kotlin 的新手。当按下作为 RecyclerView 一部分的按钮时,我正在尝试使用 AlertDialog 框。在 MainActivity 中调用 RecylerView 适配器。
下面是我在适配器中的代码。为 AlertDialog.Builder(this) 的上下文使用“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()
....
}
【问题讨论】:
-
将上下文作为参数添加到您的适配器
-
@Yoleth 在大多数情况下都有效,但在基本活动被破坏的情况下仍然会抛出一些错误。
-
为什么不从活动而不是适配器渲染对话框?使用 Unit 将点击动作从适配器获取到活动中
标签: android kotlin android-recyclerview android-alertdialog android-context