How to reference anonymous inner class in Kotlin? -
this question has answer here:
i have following extension method. how can reference ongloballayoutlistener
passed addongloballayoutlistener()
method? need pass listener removeongloballayoutlistener()
method.
fun view.ongloballayout(callback:() -> unit ): unit{ this.viewtreeobserver.addongloballayoutlistener { if(android.os.build.version.sdk_int >= android.os.build.version_codes.jelly_bean) { this.viewtreeobserver.removeongloballayoutlistener(this); } else { this.viewtreeobserver.removeglobalonlayoutlistener(this); } callback(); } }
one way use object expression instead of lambda so:
fun view.ongloballayout(callback: () -> unit): unit { val viewtreeobserver = this.viewtreeobserver viewtreeobserver.addongloballayoutlistener(object : viewtreeobserver.ongloballayoutlistener { override fun ongloballayout() { if (android.os.build.version.sdk_int >= android.os.build.version_codes.jelly_bean) { viewtreeobserver.removeongloballayoutlistener(this); } else { viewtreeobserver.removeglobalonlayoutlistener(this); } callback(); } }) }
Comments
Post a Comment