Kotlin-如何从回调访问变量?

时间:2018-07-13 10:38:17

标签: android kotlin

我试图从回调中访问变量。

var dialog = showDialog(View.OnClickListener { dialog.dismiss() })

但是对话框显示为错误,并显示消息“未解决的引用:对话框”

这是显示完整图片的整个代码流:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonOne.setOnClickListener {
            showDialog(View.OnClickListener { Toast.makeText(this@MainActivity, "Button one clicked", Toast.LENGTH_LONG).show() })
        }

        buttonTwo.setOnClickListener {
            var dialog = showDialog(View.OnClickListener { dialog.dismiss() })
        }

    }

    private fun showDialog(clickListener: View.OnClickListener): Dialog {
        val alertDialog = AlertDialog.Builder(this@MainActivity).create()
        alertDialog.setTitle("This is title")
        alertDialog.setMessage("This is message")
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK") { _, _ -> clickListener.onClick(null) }
        alertDialog.show()
        return alertDialog
    }

}

是的,我可以打个电话关闭对话框

alertDialog.dismiss()

在showDialog方法内部。但是点击行为在不同情况下可能会有所不同。

所以我的问题是:如何从回调中访问变量?

2 个答案:

答案 0 :(得分:3)

这是您想要的吗?

class MainActivity : AppCompatActivity() {

    lateinit var dialog: Dialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonOne.setOnClickListener {
            showDialog(View.OnClickListener { Toast.makeText(this@MainActivity, "Button one clicked", Toast.LENGTH_LONG).show() })
        }

        buttonTwo.setOnClickListener {
            dialog = showDialog(View.OnClickListener { dialog.dismiss() })
        }

    }

    private fun showDialog(clickListener: View.OnClickListener): Dialog {
        val alertDialog = AlertDialog.Builder(this@MainActivity).create()
        alertDialog.setTitle("This is title")
        alertDialog.setMessage("This is message")
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK") { _, _ -> clickListener.onClick(null) }
        alertDialog.show()
        return alertDialog
    }

}

现在您可以在dialog中的任何地方访问MainActivity

答案 1 :(得分:0)

使用Anko和Kotlin的语法,可以使代码更加简单和紧凑:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonOne.setOnClickListener { showDialog { toast("Button one clicked") } }
        buttonTwo.setOnClickListener { showDialog { it.dismiss() } }
    }

    private fun showDialog(func: (DialogInterface) -> Unit) =
        alert(Appcompat, "This is message") {
            title = "This is title"
            okButton { func(it) }
        }.show()
}