Android Can';无法从匿名类访问外部类
我无法从匿名方法的内部访问外部方法Android Can';无法从匿名类访问外部类,android,kotlin,Android,Kotlin,我无法从匿名方法的内部访问外部方法 class MyClass() { fun doSomeStuff() { for (brandView in holder.brandImages) { brandView.onClick { if (brandView.brandId != null) { notifyStateChanged(
class MyClass()
{
fun doSomeStuff()
{
for (brandView in holder.brandImages)
{
brandView.onClick {
if (brandView.brandId != null)
{
notifyStateChanged()
}
}
}
}
fun notifyStateChanged()
{
print("something")
}
}
我得到编译时错误:
Error:(46, 31) org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Don't know how to generate outer expression for class <closure-BrandsBarView$1>
Cause: Don't know how to generate outer expression for class <closure-BrandsBarView$1>
File being compiled and position: (46,31) in C:/Users/piotr/IdeaProjects/MerciIt/app/src/main/java/pl/com/digita/merciit/app/ui/controls/colorswitcher/brandsbar/BrandsBarView.kt
PsiElement: {
if (brandView.brandId != null)
{
notifyStateChanged()
//brandView.setTicked(!brandView.isTicked)
}
}
The root cause was thrown at: CodegenContext.java:160
at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:299)
(...)
在匿名类中工作正常
此
指外部类。
必须明确引用来自对象的外部活动
class MainActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?) {
...
text_view.setOnClickListener{ v ->
this.doActivityStuff()
}
...
fun doActivityStuff() {
// do some stuff
}
text_view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
this.onClick(v) // this refer to onClickListener
this@MainActivity.doActivityStuff() // this refer to MainActivity
}
})
}
为了帮助您解决这个问题,最好能看到类的层次结构。感谢您的评论,我添加了一些代码行,以便为这个snipplet提供更好的上下文。我也尝试过使用限定的方法,但没有成功。另外,请提供brandView classIf如果您遇到了如上所述的编译器崩溃,您应该将崩溃报告给,因为这不是代码语法问题。
class MainActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?) {
...
text_view.setOnClickListener{ v ->
this.doActivityStuff()
}
...
fun doActivityStuff() {
// do some stuff
}
text_view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
this.onClick(v) // this refer to onClickListener
this@MainActivity.doActivityStuff() // this refer to MainActivity
}
})
}