android - Kotlin - 如何创建类似于 TextView.setText(String) 的类成员函数,可以调用为 TextView.text = ""

标签 android kotlin

我要创建的是自定义 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 = ""。这可以为自定义类完成吗...?

最佳答案

你需要定义一个属性:

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

关于android - Kotlin - 如何创建类似于 TextView.setText(String) 的类成员函数,可以调用为 TextView.text = "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53387642/

相关文章:

java - 正则表达式在intellij idea中编译,但不在android studio中编译并显示

java - 循环中的结果回调(从谷歌驱动器下载多张图片。)

java - 使用Kotlin编译Java代码时报错: generics are not supported in -source 1. 3

android - Android开发中如何正确处理View State

java - 使用 ContentResolver 检索 SMS 的 NullPointerException 导致应用程序崩溃

android - 将Gradle项目导入Eclipse

java - 无法使用 'com.google.android.gms:play-services:9.4.0' 构建 APK

java - 获取两个不同日期的日期范围

intellij-idea - IntelliJ 删除后无法识别 kotlin 文件并使用相同名称重新创建

android - 打开软键盘时,Android Recyclerview Java.lang.NullPointerException