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

时间:2018-04-12 14:59:35

标签: android kotlin

我有一个DetailAdapter类,其参数categoryId的类型为String。我需要在内部类DetailHolder中访问此变量。我收到以下错误:

  

未解决的参考:categoryId

我该如何解决这个问题?

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

1 个答案:

答案 0 :(得分:4)

代码中的

DetailHolder嵌套类,而不是内部类(在Java中它的等价物是static嵌套类。)

要定义内部类,您需要使用inner关键字:

inner class DetailHolder( ...

这种方式DetailHolder将包含对其封闭类(DetailAdapter)的隐式引用,您也可以访问其属性。

查看Nested and Inner Classes上的文档。