Skip to content

Commit ede876f

Browse files
Merge pull request #1 from ChristophKaser/FixMemoryLeak
Fixes a memory leak where a global layout listener is added but never…
2 parents 7454398 + 737c4d2 commit ede876f

1 file changed

Lines changed: 24 additions & 7 deletions

File tree

flowlayoutmanager/src/main/java/com/xiaofeng/flowlayoutmanager/FlowLayoutManager.java

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import android.graphics.Point;
44
import android.graphics.PointF;
55
import android.graphics.Rect;
6+
import android.support.annotation.Nullable;
67
import android.support.v7.widget.LinearSmoothScroller;
78
import android.support.v7.widget.RecyclerView;
89
import android.view.View;
@@ -29,6 +30,9 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
2930
FlowLayoutOptions newFlowLayoutOptions;
3031
LayoutHelper layoutHelper;
3132
CacheHelper cacheHelper;
33+
@Nullable
34+
private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener;
35+
3236
public FlowLayoutManager() {
3337
flowLayoutOptions = new FlowLayoutOptions();
3438
newFlowLayoutOptions = FlowLayoutOptions.clone(flowLayoutOptions);
@@ -468,17 +472,30 @@ public void onAttachedToWindow(final RecyclerView view) {
468472
layoutHelper = new LayoutHelper(this, recyclerView);
469473
cacheHelper = new CacheHelper(flowLayoutOptions.itemsPerLine, layoutHelper.visibleAreaWidth());
470474
if (layoutHelper.visibleAreaWidth() == 0) {
471-
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
472-
@Override
473-
public void onGlobalLayout() {
474-
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
475-
cacheHelper.contentAreaWidth(layoutHelper.visibleAreaWidth());
476-
}
477-
});
475+
if (globalLayoutListener == null) {
476+
globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
477+
@Override
478+
public void onGlobalLayout() {
479+
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
480+
globalLayoutListener = null;
481+
cacheHelper.contentAreaWidth(layoutHelper.visibleAreaWidth());
482+
}
483+
};
484+
}
485+
view.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
478486
}
479487

480488
}
481489

490+
@Override
491+
public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
492+
super.onDetachedFromWindow(view, recycler);
493+
if (globalLayoutListener != null) {
494+
view.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
495+
globalLayoutListener = null;
496+
}
497+
}
498+
482499
@Override
483500
public boolean supportsPredictiveItemAnimations() {
484501
return true;

0 commit comments

Comments
 (0)