简体   繁体   English

Kotlin:内部类如何访问在外部类中声明为参数的变量?

[英]Kotlin: How can an inner class get access to a variable declared as a parameter in an outer class?

I have a DetailAdapter class with a parameter categoryId of type String . 我有一个DetailAdapter类,其参数categoryId类型为String I need access to this variable in the inner class DetailHolder . 我需要在内部类DetailHolder访问此变量。 I get the following error: 我收到以下错误:

Unresolved reference: categoryId 未解决的参考:categoryId

How can I solve this? 我怎么解决这个问题?

class DetailAdapter(lifecycleOwner: LifecycleOwner, categoryId: String) : FirebaseRecyclerAdapter<Detail, DetailAdapter.DetailHolder>(DetailAdapter.buildOptions(lifecycleOwner, categoryId)) {

companion object {
    private fun buildQuery(categoryId: String) = FirebaseDatabase.getInstance()
            .reference
            .child("").child("details").child(categoryId)
            .limitToLast(50)

    private fun buildOptions(lifecycleOwner: LifecycleOwner, categoryId: String) = FirebaseRecyclerOptions.Builder<Detail>()
            .setQuery(buildQuery(categoryId), Detail::class.java)
            .setLifecycleOwner(lifecycleOwner)
            .build()
}

class DetailHolder(val customView: View, var detail: Detail? = null) : RecyclerView.ViewHolder(customView) {
    private val TAG = DetailHolder::class.java.simpleName

    fun bind(detail: Detail) {
        with(detail) {
            customView.textView_name?.text = detail.detailName
            customView.textView_description?.text = detail.detailDescription

            val detailId = detail.detailId

            customView.setOnClickListener {
                    // do something
            }

            customView.setOnLongClickListener(
                    {
                        showDeleteDetailDialog(it, categoryId, detailId)
                        true
                    }
            )
        }
    }

DetailHolder in your code is a nested class, not an inner one (its equivalent in Java would be a static nested class). 代码中的DetailHolder是一个嵌套类,而不是内部类(它在Java中的等价物将是一个static嵌套类)。

To define an inner class you need to use the inner keyword: 要定义内部类,您需要使用inner关键字:

inner class DetailHolder( ...

This way DetailHolder will hold an implicit reference to its enclosing class ( DetailAdapter ) and you'll be able to access its properties as well. 这样, DetailHolder将保持对其封闭类( DetailAdapter )的隐式引用,您也可以访问其属性。

Check out the documentation on Nested and Inner Classes . 查看有关嵌套和内部类的文档。

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

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