首页 > 解决方案 > 在两个警报对话框之间传递信息

问题描述

第一个警报对话框中的 ImageView 打开第二个对话框以更改第一个对话框中 ImageView 的 imageResource。但是我不知道如何在两个警报对话框之间建立联系

两者都有不同的 xml 布局,所以我假设在第二个对话框中我应该参考第一个对话框的布局

private fun editItemDialog() {
    val dialogBuilder1 = AlertDialog.Builder(this)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.edit_dialog, null)
    dialogBuilder1.setView(dialogView)

    var editIconButton = dialogView.findViewById<View>(R.id.editIcon) as ImageView

    editIconButton.setOnClickListener{
        showIconDialog()

    }



    dialogBuilder1.setTitle("Edit mode")
    dialogBuilder1.setPositiveButton("Save") { _, _ ->
       //sth
    }
    dialogBuilder1.setNegativeButton("Cancel") { _, _ ->
       //sth
    }
    val b = dialogBuilder1.create()
    b.show()
}     

private fun showIconDialog() {
    val dialogBuilder = AlertDialog.Builder(this)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.icons, null)
    dialogBuilder.setView(dialogView)

    //examplary two icons to select

    var travelRB = dialogView.findViewById<View>(R.id.travel) as RadioButton

    var travRB = dialogView.findViewById<View>(R.id.travel) as RadioButton


    dialogBuilder.setTitle("Icon dialog")
    dialogBuilder.setMessage("Select an icon")
    dialogBuilder.setPositiveButton("Save") { _, _ ->
         //here I would like to change an icon of the ImageView, for example:
         editIconButton.setImageResource(R.id.travel)

    dialogBuilder.setNegativeButton("Cancel") { _, _ ->
        //sth
    }
    val b = dialogBuilder.create()
    b.show()


}

标签: androidkotlinandroid-alertdialog

解决方案


您可以向第二个对话框添加回调

fun showIconDialog(callback : (Drawable) -> Unit) { 
        //code 
        callback.invoke(someDrawable)
    }

在第一个上,您只需执行以下操作:

showIconDialog() { someDrawable ->
        //code to change the layout src icon
    }

推荐阅读