欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Kotlin 接口回调示例

程序员文章站 2022-05-01 19:11:06
1. 只有一个方法时://接口定义:private var onDeleteListener: ((String) -> Unit)? = null fun setOnDeleteListener(onDeleteListener: ((String) -> Unit)) { this.onDeleteListener = onDeleteListener } // 使用onDeleteListener?.invoke("delete")...

1. 只有一个方法时:


//接口定义:
private var onDeleteListener: ((String) -> Unit)? = null

    fun setOnDeleteListener(onDeleteListener: ((String) -> Unit)) {
        this.onDeleteListener = onDeleteListener
    }
    
// 使用
onDeleteListener?.invoke("delete")


//外部使用:
deleteDialog.setOnDeleteListener {
               Log.e("1111", "setOnDeleteListener:$it")
            }

2. 多于一个方法时:

==================================================
//仿java写法
interface DialogListener {
        fun dismiss()
        fun confirm()
    }

private var dialogListener : DialogListener ? = null

    fun setDialogListener(dialogListener: DialogListener){
        this.dialogListener = dialogListener 
    }    
//使用
dialogListener ?.confirm()
dialogListener ?.dismiss()

//外部调用
 dialog.setDialogListener(object : UnplacedDialog.DialogListener {
            override fun dismiss() {
            }

            override fun confirm() {
            }

        })
==================================================

//Kotlin写法(DSL)
inner class ListenerBuilder {
        internal var dismissAction: (() -> Unit)? = null
        internal var confirmAction: (() -> Unit)? = null

        fun dismiss(action: () -> Unit) {
            dismissAction = action
        }

        fun confirm(action: () -> Unit) {
            confirmAction = action
        }
    }
    
private var mListener: ListenerBuilder? = null

    fun addUDialogListener(listenerBuilder: ListenerBuilder.() -> Unit) {
        mListener = ListenerBuilder().also(listenerBuilder)
    }

//使用
mListener?.confirmAction?.invoke()
mListener?.dismissAction?.invoke()

//外部调用
dialog.addDialogListener {
            dismiss {
              
            }
            confirm {
            
        }
}

本文地址:https://blog.csdn.net/ssq236811/article/details/108724138

相关标签: Android Kotlin