如何在Kotlin的Adapter中调用AlertDialog.Builder()时设置Context?

问题描述 投票:0回答:1

我是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()
....
}
android kotlin android-recyclerview android-alertdialog android-context
1个回答
2
投票

视图有一个引用 Context因此,下面的内容应该是可行的。

fun reminderButtonClicked(view: View) {
  reminderAlertDialog(view.context)
}

fun reminderAlertDialog(context: Context) {
  val dialog = AlertDialog.Builder(context)
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.