簡體   English   中英

class 中的 Kotlin 內部接口聲明

[英]Kotlin inner interface declaration in class

I'm newby in Kotlin and need to re-write the following Java class to Kotlin, and can't figure it out how to implement it.

public class TestFragment extends ListFragment {
        
        static interface Listener {
            void itemClicked(long id);
        };


        private Listener listener;



   .....
}

這樣就可以在@Ovveride onAttach(..) 方法中使用“監聽器”作為

override fun onAttach(Context context) {
super.onAttach(context)
listener = context as Listener
}

-----------------更新---------

class TestFragment: ListFragment() {

    internal interface Listener {
        fun itemClicked(id: Long)
    }

    private var listener: Listener? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as Listener
    }

    override fun onListItemClick(listView: ListView, itemView: View, position: Int, id: Long) {
        if (listener != null) {
            listener!!.itemClicked(id)
        }
    }

如果您使用的是 Android Studio,並且將此代碼復制粘貼到 IDE 中,它會自動詢問您是否希望它自己將其轉換為 Kotlin。

試試看。

不過,如果您嘗試在 Kotlin 中創建單功能接口,我建議您改用高階 function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM