首页 > 解决方案 > Kotlin - 如何创建类似于 TextView.setText(String) 的类成员函数,可以作为 TextView.text = "" 调用

问题描述

我要创建的是一个自定义 AlertDialogBox,我想为其调用“setTitle()”方法作为alertObject.title = "SomeTitle". 我当前的 AlertDialog 代码如下

class AlertBox(context: Context) : BaseDialogHelper() {

override val dialogView: View by lazy {
    LayoutInflater.from(context).inflate(R.layout.custom_dialog, null)
}

override val builder: AlertDialog.Builder = AlertDialog.Builder(context).setView(dialogView)

val txt_title: TextView by lazy {
    dialogView.findViewById<TextView>(R.id.txt_title)
}

val txt_message: TextView by lazy {
    dialogView.findViewById<TextView>(R.id.txt_message)
}

val btn_ok: Button by lazy {
    dialogView.findViewById<Button>(R.id.btn_done)
}

val btn_cancel: Button by lazy {
    dialogView.findViewById<Button>(R.id.btn_cancel)
}

//These are the methods that i want to change
fun setTitle(title: String) {
    txt_title.text = title
}

fun setMessage(message: String) {
    txt_message.text = message
}


fun onOkButtonClickListener(func: (() -> Unit)? = null) = with(btn_ok) {
    setClickListenerToButton(func)
}

fun onCancelButtonClickListener(func: (() -> Unit)? = null) = with(btn_cancel) {
    setClickListenerToButton(func)
}


private fun View.setClickListenerToButton(func: (() -> Unit)?) = setOnClickListener {
    func?.invoke()
    dialog?.dismiss()
}


}

我想创建一个类似于 TextView.setText(String) 的类成员函数,可以作为 TextView.text = "" 调用。这可以为自定义类完成......?

标签: androidkotlin

解决方案


您需要定义一个属性:

var text: String
    get() = txt_title.text
    set(value) { txt_title.text = value }

推荐阅读