Skip to content

Commit

Permalink
Fix Memory Leak with setOnApplyWindowInsetsListener. (#569)
Browse files Browse the repository at this point in the history
  • Loading branch information
vanniktech authored Apr 8, 2022
1 parent 9275767 commit d6cce7b
Showing 1 changed file with 38 additions and 25 deletions.
63 changes: 38 additions & 25 deletions emoji/src/main/java/com/vanniktech/emoji/EmojiPopup.java
Original file line number Diff line number Diff line change
Expand Up @@ -163,31 +163,7 @@
}

void start() {
context.getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
int previousOffset;

@Override public WindowInsets onApplyWindowInsets(final View v, final WindowInsets insets) {
final int offset;

if (insets.getSystemWindowInsetBottom() < insets.getStableInsetBottom()) {
offset = insets.getSystemWindowInsetBottom();
} else {
offset = insets.getSystemWindowInsetBottom() - insets.getStableInsetBottom();
}

if (offset != previousOffset || offset == 0) {
previousOffset = offset;

if (offset > Utils.dpToPx(context, MIN_KEYBOARD_HEIGHT)) {
updateKeyboardStateOpened(offset);
} else {
updateKeyboardStateClosed();
}
}

return context.getWindow().getDecorView().onApplyWindowInsets(insets);
}
});
context.getWindow().getDecorView().setOnApplyWindowInsetsListener(new EmojiPopUpOnApplyWindowInsetsListener(this));
}

void stop() {
Expand Down Expand Up @@ -511,4 +487,41 @@ static final class EmojiPopUpOnAttachStateChangeListener implements View.OnAttac
v.removeOnAttachStateChangeListener(this);
}
}

static final class EmojiPopUpOnApplyWindowInsetsListener implements View.OnApplyWindowInsetsListener {
private final WeakReference<EmojiPopup> emojiPopup;
int previousOffset;

EmojiPopUpOnApplyWindowInsetsListener(final EmojiPopup emojiPopup) {
this.emojiPopup = new WeakReference<>(emojiPopup);
}

@Override public WindowInsets onApplyWindowInsets(final View v, final WindowInsets insets) {
final EmojiPopup popup = emojiPopup.get();

if (popup != null) {
final int offset;

if (insets.getSystemWindowInsetBottom() < insets.getStableInsetBottom()) {
offset = insets.getSystemWindowInsetBottom();
} else {
offset = insets.getSystemWindowInsetBottom() - insets.getStableInsetBottom();
}

if (offset != previousOffset || offset == 0) {
previousOffset = offset;

if (offset > Utils.dpToPx(popup.context, MIN_KEYBOARD_HEIGHT)) {
popup.updateKeyboardStateOpened(offset);
} else {
popup.updateKeyboardStateClosed();
}
}

return popup.context.getWindow().getDecorView().onApplyWindowInsets(insets);
}

return insets;
}
}
}

0 comments on commit d6cce7b

Please sign in to comment.