本文介绍了无法从innerclass访问变量:Kotlin Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android Kotlin开发的新手.在这里,我尝试从其内部类访问类中定义的变量,如下所示.

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内部,它不允许我访问外部范围的任何变量.

inside inner class MyViewHolder it is not allowing me to access any variable of outer scope.

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

even I'm unable to access view ids imported from import kotlinx.android.synthetic.main.activity_main.* inside inner class methods.

我能够在java中以这种方式访问​​变量,但是我已经阅读了很多关于stackoverflow的问题,但是我还没有得到答案.

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.

推荐答案

您应该在适配器中使用inner修饰符.

You should use the inner modifier in your adapter.

此修饰符使内部类可以访问外部类的成员

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

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

这篇关于无法从innerclass访问变量:Kotlin Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:37