How to reference “this” within anonymous listeners when using short notation?

后端 未结 3 1785
北海茫月
北海茫月 2021-01-04 04:38

In Kotlin, is there a way to reference the listener instance when using this short notation for anonymous classes? In this case this refers to outer context (e.

相关标签:
3条回答
  • 2021-01-04 04:53
     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
            }
        }
    
    0 讨论(0)
  • 2021-01-04 04:57

    You can get that resolved by adding an @ActivityName in front of 'this' reference For example if your Activity name was MainActivity the solution would be:

    view.setOnClickListener {
        val self: View.OnClickListener = this@MainActivity 
    }
    
    0 讨论(0)
  • 2021-01-04 05:07

    The term short notation for anonymous classes is not entirely correct. It's actually a short notation for anonymous functions, i.e. lambdas. Of course under the hood they are compiled to classes but from a programming language point of view, anonymous functions don't have identities and therefore it doesn't make sense to refer to their instances via this.

    0 讨论(0)
提交回复
热议问题