简体   繁体   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. 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;



   .....
}

So that to use "listener" in @Ovveride onAttach(..) methods as这样就可以在@Ovveride onAttach(..) 方法中使用“监听器”作为

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

----------------- UPDATE -------------------- -----------------更新---------

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

If you're using Android Studio, and you copy-paste this code into your IDE, it will automatically ask you if you want it to convert it into Kotlin on its own.如果您使用的是 Android Studio,并且将此代码复制粘贴到 IDE 中,它会自动询问您是否希望它自己将其转换为 Kotlin。

Try that out.试试看。

Nevertheless, if you're trying to create a one-function interface in Kotlin I would recommend you use a High-Order function instead.不过,如果您尝试在 Kotlin 中创建单功能接口,我建议您改用高阶 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM