equivalent implementing java interface on kotlin

2019-09-15 16:58发布

问题:

I'm newbie in Kotlin and i'm trying to know how can i implementing java interface on kotlin, i'm using that on android,

public interface OnClickedItemListener {
    void onClick(boolean state);
}

OnClickedItemListener is my custom interface which i want to implementing that, in kotlin i have this class:

class MyProgressView : RelativeLayout {
    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)
        cusotmView.setOnClickListener {
        }
    }
}

in that whats equivalent this cods for example:

class MyProgressView : RelativeLayout {
    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)
        cusotmView.setOnClickListener {
            /*
            if(onitemClickListener!=null) onitemClickListener.onClick()
            */
        }
    }

    /*
    public interface OnitemClickListener{
        void onClick();
    }

    public static void setOnitemClickListener(OnitemClickListener listener){
        onitemClickListener = l;
    }
    */

}

回答1:

use setOnClickItemListener in your Activity.

class MyProgressView : RelativeLayout, OnClickedItemListener  {

    var onClickItemListener: OnClickedItemListener? = null

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

    override fun onClick(state: Boolean) {
        //do something on onclick
    }

    fun setOnClickedItemListener(onclickItemListener: OnClickedItemListener) {
        this.onClickItemListener = onclickItemListener
    }

}

I hope this may help you.