如何在使用短符号时在匿名监听器中引用“this”?

在Kotlin中,当匿名类使用这个简短符号时,有没有办法引用监听器实例? 在这种情况下, this是指定义view外部上下文(例如, Activity实例):

 view.setOnClickListener { val self: View.OnClickListener = this // Not compiling, "this" references outer context } 

如果在明确声明要实现的接口的地方使用较长的符号,并在显式重写回调方法的地方使用,则可以通过this方法引用监听器:

 view.setOnClickListener(object: View.OnClickListener { override fun onClick(v: View) { val self: View.OnClickListener = this // Ok } }) 

匿名类的简称是不完全正确的。 这实际上是匿名函数的简称,即lambda。 当然,它们被编译为类,但是从编程语言的角度来看,匿名函数没有标识,因此通过它来引用它们的实例是没有意义的。

  val animation = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { val layoutParam: RelativeLayout.LayoutParams? = playerView.layoutParams as RelativeLayout.LayoutParams? layoutParam?.topMargin = convertDpToPixel(position, this@SurahActivity).toInt() playerView.layoutParams = layoutParam } }