I am new to Kotlin development in android. here I am trying to access a variable defined in a class from it's inner class as below.

class MainActivity : AppCompatActivity() {

    var frags: MutableList<Fragment> = mutableListOf()

//.............onCreate and other methods ....

    internal class CustAdapter(var arrayList: ArrayList<NavigationData>) : RecyclerView.Adapter<CustAdapter.MyViewHolder>() {
    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
        holder!!.bindItems(arrayList[position])
    }

    override fun getItemCount(): Int {
        return arrayList.size
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustAdapter.MyViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.navigation_item, parent, false)
        return MyViewHolder(v)
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindItems(data: NavigationData) {


            itemView.setOnClickListener {
                   frags.add(BoardFrag()) ///// here i'm getting error "unresolved symbol"

            }
        }
    }
}    
}

在内部类MyViewHolder中,它不允许我访问外部范围的任何变量.

即使我也无法访问从 import kotlinx.android.synthetic.main.activity_main.*个内部类方法导入的视图ID.

I was able to access variables in such a way in java but i have read many question on stackoverflow but i didn't get answer yet.

推荐答案

You should use the inner modifier in your adapter.

This modifier makes the inner class have access to the members of the outer class

Reference: https://kotlinlang.org/docs/reference/nested-classes.html

Kotlin相关问答推荐

在没有外部 map 的情况下转换列表项

来自SnapshotFlow的单元测试StateFlow仅发出initialValue

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

用普通Kotlin理解Gradle的Kotlin DSL'""

jOOQ Kotlin Coroutines - Select all and exists查询

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

Kotlin SAM/功能接口抛出 AbstractMethodError

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

Kotlin 中的 Java Scanner 相当于什么?

如何从不同的功能发出流量值? Kotlin 协程

`DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别

TextField maxLength - Android Jetpack Compose

Kotlin:如何在活页夹中返回正在运行的服务实例?

将 @Component.Builder 与构造函数参数一起使用

Kotlin内联扩展属性

如果 Maybe 完成,则从其他来源将 Maybe 转换为 Single

如何从协程范围返回值

Kotlin - computed var 属性的用处?

WebFlux 功能:如何检测空 Flux 并返回 404?