Skip to content

Commit

Permalink
Fix onGlobalLayoutListener leak (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmazzoni authored and natario1 committed Feb 28, 2019
1 parent 73c0429 commit 0044303
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions library/src/main/java/com/otaliastudios/zoom/ZoomLayout.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import android.content.Context
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.*
import android.widget.FrameLayout
import androidx.annotation.AttrRes
import com.otaliastudios.zoom.ZoomApi.ZoomType
Expand All @@ -32,7 +29,7 @@ import com.otaliastudios.zoom.ZoomApi.ZoomType
*/
open class ZoomLayout
private constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int, val engine: ZoomEngine = ZoomEngine(context))
: FrameLayout(context, attrs, defStyleAttr), ZoomEngine.Listener, ZoomApi by engine {
: FrameLayout(context, attrs, defStyleAttr), ViewTreeObserver.OnGlobalLayoutListener, ZoomEngine.Listener, ZoomApi by engine {

@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0)
Expand Down Expand Up @@ -85,6 +82,24 @@ private constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAtt

//region Internal

override fun onGlobalLayout() {
if (childCount == 0) {
return
}
val child = getChildAt(0)
engine.setContentSize(child.width.toFloat(), child.height.toFloat())
}

override fun onAttachedToWindow() {
super.onAttachedToWindow()
viewTreeObserver.addOnGlobalLayoutListener(this)
}

override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
viewTreeObserver.removeOnGlobalLayoutListener(this)
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

// Measure ourselves as MATCH_PARENT
Expand All @@ -103,12 +118,10 @@ private constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAtt
}

override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) {
if (childCount == 0) {
child.viewTreeObserver.addOnGlobalLayoutListener { engine.setContentSize(child.width.toFloat(), child.height.toFloat()) }
super.addView(child, index, params)
} else {
if (childCount > 0) {
throw RuntimeException("$TAG accepts only a single child.")
}
super.addView(child, index, params)
}

override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
Expand Down

0 comments on commit 0044303

Please sign in to comment.