我无法从Kotlin的嵌套课程中找到任何班级成员 [英] I can't reach any class member from a nested class in Kotlin

查看:78
本文介绍了我无法从Kotlin的嵌套课程中找到任何班级成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从PersonAdapter类访问MainFragment类的成员,但是它们都不可用.我尝试过将班级和成员都设为公开和私有,但到目前为止没有任何效果. 我想我遗漏了一些明显的东西,但我无法弄清楚.

I want to access a member of the MainFragment class from PersonAdapter class but none of them are available. I tried making both the classes and the members public and private also but so far nothing worked. I guess I'm missing something obvious but I just can't figure it out.

class MainFragment : Fragment() {
    lateinit var personAdapter: PersonAdapter
    lateinit var personListener: OnPersonSelected
    private var realm: Realm by Delegates.notNull()
    lateinit var realmListener: RealmChangeListener<Realm>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.fragment_main, container, false)
        return v
    }

    class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        var localPersonList = personList

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bindItems(localPersonList[position])

            holder.itemView.setOnClickListener {
                Toast.makeText(context, "click", Toast.LENGTH_SHORT).show()
                //I want to reach personListener from here
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
            val v = LayoutInflater.from(parent!!.context).inflate(R.layout.person_list_item, parent, false)
            return ViewHolder(v)
        }
    }}

推荐答案

在Kotlin中,嵌套类默认情况下无法访问外部类实例,就像Java中的嵌套static class es一样.

In Kotlin, nested classes cannot access the outer class instance by default, just like nested static classes in Java.

为此,请将 inner 修饰符添加到嵌套类:

To do that, add the inner modifier to the nested class:

class MainFragment : Fragment() {
    // ...

    inner class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        // ...
    }
}

请参见: 嵌套类 参考

See: Nested classes in the language reference

这篇关于我无法从Kotlin的嵌套课程中找到任何班级成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆