2017-07-24 57 views
0

我是新手在Kotiln和这个代码是简单的类,我在Android上使用。在这个类中,我想让一个简单的侦听器来检测类中的项目点击,例如活动,片段或适配器。我的问题是,我可以为circularProgressView小部件定义此侦听器。Kotlin添加自定义侦听器在Android上点击小部件

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(); 
     } 
    } 
} 

如何知道用户是否点击了circularProgressView内部活动?

我想要实现此接口并使用它里面科特林:

public interface OnItemClickListener { 
    void onClick(int position); 
} 

回答

1

init的progreessListener使用下面的代码

var progressListener: OnItemClickListener? = null 
set 

对于呼叫使用onclick:progressListener?.onClick(downloading)

接口文件:

public interface OnItemClickListener { 

void onClick(boolean download); 

} 

为了实现你的界面使用下面的代码:

var onItemClickInterface : OnItemClickListener = object : OnItemClickListener { 
    override fun onClick(download: Boolean) { 
     TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 
    } 
} 
+0

感谢,我的活动与Java实现,如何设置这个监听器?例如:'public static void setOnItemClickListener(OnItemClickListener lst){progressListener = l}'并从活动例如'DownloadProgressView.setOnItemClickInterface(new ...){}' –

+0

使用静态setListener它是最好的想法。 –

+0

你可以更新你的帖子吗? –

相关问题