Kotlin 为在 android 上单击的小部件添加自定义侦听器

Dol*_*rma 0 android kotlin

我是 Kotiln 的新手,这段代码是我在 Android 上使用的简单类。在这个类中,我想制作简单的侦听器来检测对类内项目的点击,例如活动、片段或适配器。我的问题是我可以为circularProgressView小部件定义这个监听器。

class DownloadProgressView : RelativeLayout {

    var progressListener: ((downloading: Boolean) -> Unit)? = null
    private var downloading = false

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        LayoutInflater.from(context).inflate(R.layout.download_progress_layout, this)
        circularProgressView.setOnClickListener {
            downloading = !downloading
            setProgressViews(downloading)
            progressListener?.invoke(downloading)

            //if listener!=null then onItemClicked.onClick();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么知道用户是否点击了circularProgressView内部活动?

我正在尝试实现这个接口并在 Kotlin 中使用它:

public interface OnItemClickListener {
    void onClick(int position);
}
Run Code Online (Sandbox Code Playgroud)

Vov*_*huk 6

对于 init processListener 使用以下代码

var listener: () -> Unit = {}
Run Code Online (Sandbox Code Playgroud)

对于调用 onClick 使用: listener()

要实现您的界面,请使用以下代码:

var onItemClickInterface : () -> Unit = {
  //TODO
}
Run Code Online (Sandbox Code Playgroud)