在两个警告对话框之间传递信息

3

第一个对话框中的ImageView打开第二个对话框以更改第一个对话框中ImageView的图像资源。但是我不知道如何在两个对话框之间建立连接。

两个对话框具有不同的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()


}
1个回答

4
您可以为第二个对话框添加回调函数。
fun showIconDialog(callback : (Drawable) -> Unit) { 
        //code 
        callback.invoke(someDrawable)
    }

对于第一个,你只需要这样做:

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

我必须承认,使用回调函数对我来说是新的。在“someDrawable”之外,我应该放什么? - Mark
你应该将图标添加为Drawable(例如)ContextCompat.getDrawable(context, R.drawable.iconFile)。 - Diogo Rosa
在我添加评论的第一个对话框中,您可以添加editIconButton.backgroundDrawable(someDrawable)。 - Diogo Rosa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接