2017-07-24 53 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

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

相關問題