[英]Unable to access variable from innerclass : Kotlin android
I am new to Kotlin development in android.我是 android 中 Kotlin 开发的新手。 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"
}
}
}
}
}
inside inner class MyViewHolder
it is not allowing me to access any variable of outer scope.在内部类MyViewHolder
它不允许我访问外部作用域的任何变量。
even I'm unable to access view ids imported from import kotlinx.android.synthetic.main.activity_main.*
inside inner class methods.即使我无法访问从内部类方法中的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.我能够在java
以这种方式访问变量,但我已经阅读了很多关于 stackoverflow 的问题,但我还没有得到答案。
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参考: https : //kotlinlang.org/docs/reference/nested-classes.html
Define your nested class as inner
then you will be able to access an outer class member variable.将嵌套类定义为inner
类,然后您将能够访问外部类成员变量。
class OuterClass{
var accessMe ="access me from Inner Class"
inner class InnerClass{
//....
fun accessingOuterClassVariable(){
accessMe = "Now the variable is accessed"
}
}
}
to answer this question for the fast an easy way i would do something like following :要以一种简单的方式快速回答这个问题,我会执行以下操作:
class OuterClass{
private var accessibleInside: CustomObject? = null
inner class InnerClass{
//....
}
now the CustomObject
could be anything from Context
to String
hope this helps someone.现在CustomObject
可以是从Context
到String
任何东西,希望这对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.