Skip to content

Commit

Permalink
[SnackBar] Fix margins are added multiple times when show() is called
Browse files Browse the repository at this point in the history
When a snack bar is hidden and its show() method is called, it will be added to the target parent, and at this moment the parent view will set the layout params to the snack bar, with the same existing margins if any. Therefore if the margins are already updated with extra margins, the original margins will be incorrectly updated. This CL introduces a flag to tells this situation from other "real" scenarios in which clients want to update their custom margins.

Resolves #2666

PiperOrigin-RevId: 445159923
(cherry picked from commit 46fa8cc)
  • Loading branch information
drchen authored and dsn5ft committed May 4, 2022
1 parent d6cd0e6 commit 2bfc7ba
Showing 1 changed file with 12 additions and 2 deletions.
Expand Up @@ -712,7 +712,7 @@ final void showView() {
setUpBehavior((CoordinatorLayout.LayoutParams) lp);
}

targetParent.addView(this.view);
this.view.addToTargetParent(targetParent);
recalculateAndUpdateMargins();

// Set view to INVISIBLE so it doesn't flash on the screen before the inset adjustment is
Expand Down Expand Up @@ -1111,6 +1111,7 @@ public boolean onTouch(View v, MotionEvent event) {
private PorterDuff.Mode backgroundTintMode;

@Nullable private Rect originalMargins;
private boolean addingToTargetParent;

protected SnackbarBaseLayout(@NonNull Context context) {
this(context, null);
Expand Down Expand Up @@ -1233,7 +1234,10 @@ protected void onDetachedFromWindow() {
@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
super.setLayoutParams(params);
if (params instanceof MarginLayoutParams) {
if (!addingToTargetParent && params instanceof MarginLayoutParams) {
// Do not update the original margins when the layout is being added to its target parent,
// since the margins are just copied from the existing layout params, which can already be
// updated with extra margins.
updateOriginalMargins((MarginLayoutParams) params);
if (baseTransientBottomBar != null) {
baseTransientBottomBar.updateMargins();
Expand Down Expand Up @@ -1266,6 +1270,12 @@ int getMaxInlineActionWidth() {
return maxInlineActionWidth;
}

void addToTargetParent(ViewGroup targetParent) {
addingToTargetParent = true;
targetParent.addView(this);
addingToTargetParent = false;
}

private void setBaseTransientBottomBar(BaseTransientBottomBar<?> baseTransientBottomBar) {
this.baseTransientBottomBar = baseTransientBottomBar;
}
Expand Down

0 comments on commit 2bfc7ba

Please sign in to comment.