我无法从Kotlin的嵌套课程中找到任何班级成员

我无法从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