From e44d2ba718eebfdabb694c942800dc834366fdb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Meitner?= Date: Mon, 23 Nov 2026 08:47:42 +0100 Subject: [PATCH] [Dialog] Shrink vertical background insets while the soft keyboard is shown MaterialAlertDialogBuilder insets the window background by 80dp at the top and bottom on screens taller than 480dp. The insets are fixed, so while the soft keyboard is shown, the space left above it may not hold both the insets and the dialog content. AlertDialogLayout then squeezes the custom panel, and a text field in a dialog collapses to zero height, typically with a larger display size or a smaller screen. The insets are now adjusted by VerticalBackgroundInsetsAdjuster. While the keyboard is shown, the vertical insets are shrunk proportionally to the space that the content does not need, down to zero. The configured insets are restored when the keyboard is hidden. Without the keyboard the insets are never changed, so tall dialogs keep scrolling within the configured margins. The insets are recalculated when the window is laid out and when the window insets report a change of the keyboard visibility. After a change the window attributes are reapplied, so a window using adjustPan is resized and panned for the new insets. The keyboard is detected independently of the dialog window: a dialog that fits above the keyboard no longer overlaps it, and values derived from its window would report no keyboard and make the layout oscillate. On API 30+ the visibility comes from the window insets and the keyboard height from the current window metrics. Below API 30, where WindowInsetsCompat does not report the keyboard for dialog windows, the configured screen height is compared with the visible display frame of the dialog window, limited by the visible display frame of the activity window. MaterialAlertDialogImeTest covers adjustResize, adjustPan with settling of the layout, and restoring the insets. Tested on emulators with API 23, 29, 30 and 36 at two display densities each, with dialogs from the linked issues in the default mode, adjustResize and adjustPan, and a tall list dialog without the keyboard. Closes #3418 Closes #1480 Closes #4273 Closes #4039 --- docs/components/Dialog.md | 6 + .../dialog/MaterialAlertDialogBuilder.java | 5 +- .../VerticalBackgroundInsetsAdjuster.java | 270 ++++++++++++++++++ .../VerticalBackgroundInsetsAdjusterTest.java | 87 ++++++ .../material/testapp/AndroidManifest.xml | 4 + .../testapp/MaterialAlertDialogActivity.java | 28 ++ .../dialog/MaterialAlertDialogImeTest.java | 226 +++++++++++++++ 7 files changed, 623 insertions(+), 3 deletions(-) create mode 100644 lib/java/com/google/android/material/dialog/VerticalBackgroundInsetsAdjuster.java create mode 100644 lib/javatests/com/google/android/material/dialog/VerticalBackgroundInsetsAdjusterTest.java create mode 100644 testing/java/com/google/android/material/testapp/MaterialAlertDialogActivity.java create mode 100644 tests/javatests/com/google/android/material/dialog/MaterialAlertDialogImeTest.java diff --git a/docs/components/Dialog.md b/docs/components/Dialog.md index 7630172bba2..cf6e2024e05 100644 --- a/docs/components/Dialog.md +++ b/docs/components/Dialog.md @@ -64,6 +64,12 @@ Element | Attribute **Background inset start and end** | `app:backgroundInsetStart`
`app:backgroundInsetEnd` | `setBackgroundInsetStart`
`setBackgroundInsetEnd` | `24dp` **Background inset top and bottom** | `app:backgroundInsetTop`
`app:backgroundInsetBottom` | `setBackgroundInsetTop`
`setBackgroundInsetBottom` | `80dp` +**Note:** While the soft keyboard is shown, the top and bottom background insets +of a dialog created with `MaterialAlertDialogBuilder` shrink as needed to fit +the dialog content into the space left above the keyboard. They are restored +when the keyboard is hidden. Dialog windows using `adjustPan` are adjusted +reliably on API 30+. + ### Title attributes Element | Attribute | Related methods | Default value diff --git a/lib/java/com/google/android/material/dialog/MaterialAlertDialogBuilder.java b/lib/java/com/google/android/material/dialog/MaterialAlertDialogBuilder.java index 5f134587ef3..47b27477fb5 100644 --- a/lib/java/com/google/android/material/dialog/MaterialAlertDialogBuilder.java +++ b/lib/java/com/google/android/material/dialog/MaterialAlertDialogBuilder.java @@ -162,9 +162,8 @@ public AlertDialog create() { ((MaterialShapeDrawable) background).setElevation(decorView.getElevation()); } - Drawable insetDrawable = MaterialDialogs.insetDrawable(background, backgroundInsets); - window.setBackgroundDrawable(insetDrawable); - decorView.setOnTouchListener(new InsetDialogOnTouchListener(alertDialog, backgroundInsets)); + new VerticalBackgroundInsetsAdjuster(alertDialog, window, background, backgroundInsets) + .install(); return alertDialog; } diff --git a/lib/java/com/google/android/material/dialog/VerticalBackgroundInsetsAdjuster.java b/lib/java/com/google/android/material/dialog/VerticalBackgroundInsetsAdjuster.java new file mode 100644 index 00000000000..52e3a85b394 --- /dev/null +++ b/lib/java/com/google/android/material/dialog/VerticalBackgroundInsetsAdjuster.java @@ -0,0 +1,270 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.android.material.dialog; + +import android.app.Activity; +import android.app.Dialog; +import android.content.res.Resources; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.os.Build.VERSION; +import android.os.Build.VERSION_CODES; +import android.view.View; +import android.view.View.MeasureSpec; +import android.view.View.OnLayoutChangeListener; +import android.view.Window; +import android.view.WindowInsets; +import android.view.WindowMetrics; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; +import com.google.android.material.internal.ContextUtils; + +/** + * Shrinks the vertical background insets of a dialog window while the soft keyboard is shown and + * the space left above it cannot hold both the configured insets and the dialog content. + * + *

The vertical insets are only a margin between the dialog and the edges of the screen. While + * the keyboard takes up part of the screen, the margin is given up before the content is squeezed, + * so that views such as a text field are not collapsed. The configured insets are restored when the + * keyboard is hidden. Without the keyboard the insets are never changed, so tall dialogs keep + * scrolling within the configured margins. + * + *

The insets are recalculated when the window is laid out and when the window insets report a + * change of the keyboard visibility. On API 30+, the keyboard visibility is known from the window + * insets and its height from the window metrics, independently of the size and position of the + * dialog window, so the adjusted window does not change the input of the next adjustment. Below API + * 30, the keyboard is detected from the visible display frame when the window is laid out, e.g. + * when a window using adjustResize is resized for it. Hiding the keyboard may not lay out a window + * that already fits, so the configured insets are then restored on its next layout pass; as the + * insets are transparent, this does not change how a dialog that fits the screen looks. Windows + * using adjustPan are reliably adjusted on API 30+ only. + */ +final class VerticalBackgroundInsetsAdjuster implements OnLayoutChangeListener { + + @NonNull private final Dialog dialog; + @NonNull private final Window window; + @Nullable private final Drawable background; + @NonNull private final Rect configuredInsets; + @NonNull private final Rect currentInsets; + @NonNull private final Rect visibleFrame = new Rect(); + @NonNull private final Rect activityFrame = new Rect(); + private boolean lastImeVisible; + + VerticalBackgroundInsetsAdjuster( + @NonNull Dialog dialog, + @NonNull Window window, + @Nullable Drawable background, + @NonNull Rect configuredInsets) { + this.dialog = dialog; + this.window = window; + this.background = background; + this.configuredInsets = new Rect(configuredInsets); + this.currentInsets = new Rect(configuredInsets); + } + + /** + * Applies the configured insets to the window and starts adjusting them on layout changes and on + * changes of the keyboard visibility. + */ + void install() { + applyInsets(); + View decorView = window.getDecorView(); + decorView.addOnLayoutChangeListener(this); + // Showing or hiding the keyboard does not always lay out the window: a window using + // adjustPan is not resized, and a window that fits the screen is only moved. Request a layout + // pass when the keyboard visibility changes; the default handling of the insets is kept. + ViewCompat.setOnApplyWindowInsetsListener( + decorView, + (view, insets) -> { + WindowInsetsCompat result = ViewCompat.onApplyWindowInsets(view, insets); + getVisibleFrame(visibleFrame); + boolean imeVisible = isImeVisible(view, visibleFrame); + if (imeVisible != lastImeVisible) { + lastImeVisible = imeVisible; + view.requestLayout(); + } + return result; + }); + } + + @Override + public void onLayoutChange( + @NonNull View decorView, + int left, + int top, + int right, + int bottom, + int oldLeft, + int oldTop, + int oldRight, + int oldBottom) { + int[] vertical = {configuredInsets.top, configuredInsets.bottom}; + View content = decorView.findViewById(android.R.id.content); + getVisibleFrame(visibleFrame); + if (content != null && content.getWidth() > 0 && isImeVisible(decorView, visibleFrame)) { + // Vertical padding of the decor view that does not come from the background insets. + int otherVerticalPadding = + Math.max( + decorView.getPaddingTop() + + decorView.getPaddingBottom() + - currentInsets.top + - currentInsets.bottom, + 0); + int maxContentHeight = getKeyboardTop(visibleFrame) - visibleFrame.top - otherVerticalPadding; + if (maxContentHeight > 0) { + int spareHeight = maxContentHeight - measureDesiredHeight(content, maxContentHeight); + vertical = + calculateVerticalInsets(configuredInsets.top, configuredInsets.bottom, spareHeight); + } + } + + if (vertical[0] != currentInsets.top || vertical[1] != currentInsets.bottom) { + currentInsets.top = vertical[0]; + currentInsets.bottom = vertical[1]; + updateInsets(); + } + } + + /** + * Returns the top edge of the soft keyboard in screen coordinates. + * + *

The result must not depend on the size or position of the dialog window, which change with + * the insets: a dialog that shrinks to fit above the keyboard no longer overlaps it, so values + * derived from the window (its visible display frame or its IME insets) would report that the + * keyboard is gone, the insets would be restored and the dialog would oscillate. On API 30+, the + * keyboard height is therefore taken from the metrics of the whole window area, which do not + * depend on the dialog. Below API 30, the bottom of the frame from {@link #getVisibleFrame} is + * used. + */ + private int getKeyboardTop(@NonNull Rect visibleFrame) { + if (VERSION.SDK_INT >= VERSION_CODES.R) { + WindowMetrics metrics = window.getWindowManager().getCurrentWindowMetrics(); + int imeHeight = metrics.getWindowInsets().getInsets(WindowInsets.Type.ime()).bottom; + if (imeHeight > 0) { + return metrics.getBounds().bottom - imeHeight; + } + } + return visibleFrame.bottom; + } + + /** + * Gets the visible display frame used to detect the keyboard below API 30. + * + *

The visible display frame of a window only excludes the part of the keyboard that overlaps + * the window, so the frame of the dialog window depends on the insets, see {@link + * #getKeyboardTop}. The window of the activity that shows the dialog covers the area of the + * keyboard, but it may be notified of the keyboard after the dialog window is laid out. The frame + * is therefore the frame of the dialog window, limited by the frame of the activity window. + */ + private void getVisibleFrame(@NonNull Rect outFrame) { + window.getDecorView().getWindowVisibleDisplayFrame(outFrame); + if (VERSION.SDK_INT >= VERSION_CODES.R) { + return; + } + Activity activity = ContextUtils.getActivity(dialog.getContext()); + Window activityWindow = activity != null ? activity.getWindow() : null; + View activityDecorView = activityWindow != null ? activityWindow.peekDecorView() : null; + if (activityDecorView != null && activityDecorView.isAttachedToWindow()) { + activityDecorView.getWindowVisibleDisplayFrame(activityFrame); + if (!activityFrame.isEmpty() && activityFrame.bottom < outFrame.bottom) { + outFrame.bottom = activityFrame.bottom; + } + } + } + + /** + * Returns whether the soft keyboard is shown. + * + *

On API 30+, the visibility is reported by the window insets. Below API 30, {@link + * WindowInsetsCompat} infers it from the bottom system window inset, which stays zero for a + * dialog window that is resized for the keyboard. There, the configured screen height, which + * excludes the system bars but not the keyboard, is compared with the visible display frame, + * which also excludes the keyboard. Without the keyboard they only differ by the rounding of the + * screen height to whole dp. The visible display frame is empty until the window is attached. + */ + private static boolean isImeVisible(@NonNull View decorView, @NonNull Rect visibleFrame) { + if (VERSION.SDK_INT >= VERSION_CODES.R) { + WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(decorView); + return insets != null && insets.isVisible(WindowInsetsCompat.Type.ime()); + } + if (visibleFrame.isEmpty()) { + return false; + } + Resources resources = decorView.getResources(); + float density = resources.getDisplayMetrics().density; + float screenHeight = resources.getConfiguration().screenHeightDp * density; + return screenHeight - visibleFrame.height() > density; + } + + /** + * Returns the top and bottom insets that fit into {@code spareHeight}, never exceeding the + * configured values and keeping their ratio. + */ + @VisibleForTesting + @NonNull + static int[] calculateVerticalInsets(int configuredTop, int configuredBottom, int spareHeight) { + int configuredTotal = configuredTop + configuredBottom; + if (spareHeight >= configuredTotal) { + return new int[] {configuredTop, configuredBottom}; + } + if (spareHeight <= 0) { + return new int[] {0, 0}; + } + int top = (int) ((long) configuredTop * spareHeight / configuredTotal); + return new int[] {top, spareHeight - top}; + } + + /** + * Measures the height the content wants for its current width, up to {@code maxHeight}, then + * restores its previous measurement. + * + *

An {@link MeasureSpec#AT_MOST} spec is used on purpose: with {@link + * MeasureSpec#UNSPECIFIED}, {@code AlertDialogLayout} only accounts for the minimum height of the + * button panel, which underestimates the height of stacked buttons. + */ + private static int measureDesiredHeight(@NonNull View content, int maxHeight) { + int width = content.getWidth(); + int height = content.getHeight(); + content.measure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(Math.max(maxHeight, 0), MeasureSpec.AT_MOST)); + int desiredHeight = content.getMeasuredHeight(); + content.measure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + return desiredHeight; + } + + private void applyInsets() { + Rect insets = new Rect(currentInsets); + window.setBackgroundDrawable(MaterialDialogs.insetDrawable(background, insets)); + window.getDecorView().setOnTouchListener(new InsetDialogOnTouchListener(dialog, insets)); + } + + /** + * Applies the current insets to a shown window and lets the window manager recalculate the size + * of the window, which depends on the insets. A window using adjustPan is not resized for the + * keyboard, so without this it would keep its previous size and pan offset. + */ + private void updateInsets() { + applyInsets(); + View decorView = window.getDecorView(); + decorView.post(() -> window.setAttributes(window.getAttributes())); + } +} diff --git a/lib/javatests/com/google/android/material/dialog/VerticalBackgroundInsetsAdjusterTest.java b/lib/javatests/com/google/android/material/dialog/VerticalBackgroundInsetsAdjusterTest.java new file mode 100644 index 00000000000..a76c65283e5 --- /dev/null +++ b/lib/javatests/com/google/android/material/dialog/VerticalBackgroundInsetsAdjusterTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.android.material.dialog; + +import static com.google.common.truth.Truth.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +/** Tests for {@link VerticalBackgroundInsetsAdjuster}. */ +@RunWith(RobolectricTestRunner.class) +public class VerticalBackgroundInsetsAdjusterTest { + + @Test + public void calculateVerticalInsets_enoughSpace_keepsConfiguredInsets() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(80, 80, 500)) + .asList() + .containsExactly(80, 80) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_exactlyEnoughSpace_keepsConfiguredInsets() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(80, 80, 160)) + .asList() + .containsExactly(80, 80) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_notEnoughSpace_shrinksInsetsToSpareHeight() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(80, 80, 101)) + .asList() + .containsExactly(50, 51) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_asymmetricInsets_keepsRatio() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(30, 90, 60)) + .asList() + .containsExactly(15, 45) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_noSpareHeight_removesInsets() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(80, 80, 0)) + .asList() + .containsExactly(0, 0) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_contentTallerThanWindow_removesInsets() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(80, 80, -40)) + .asList() + .containsExactly(0, 0) + .inOrder(); + } + + @Test + public void calculateVerticalInsets_noConfiguredInsets_staysZero() { + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(0, 0, -40)) + .asList() + .containsExactly(0, 0) + .inOrder(); + assertThat(VerticalBackgroundInsetsAdjuster.calculateVerticalInsets(0, 0, 100)) + .asList() + .containsExactly(0, 0) + .inOrder(); + } +} diff --git a/testing/java/com/google/android/material/testapp/AndroidManifest.xml b/testing/java/com/google/android/material/testapp/AndroidManifest.xml index 5fbd208868b..af16e433cc2 100644 --- a/testing/java/com/google/android/material/testapp/AndroidManifest.xml +++ b/testing/java/com/google/android/material/testapp/AndroidManifest.xml @@ -55,6 +55,10 @@ android:name=".BottomSheetDialogActivity" android:theme="@style/Theme.AppCompat.NoActionBar"/> + + diff --git a/testing/java/com/google/android/material/testapp/MaterialAlertDialogActivity.java b/testing/java/com/google/android/material/testapp/MaterialAlertDialogActivity.java new file mode 100644 index 00000000000..747e4df2a14 --- /dev/null +++ b/testing/java/com/google/android/material/testapp/MaterialAlertDialogActivity.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.android.material.testapp; + +import com.google.android.material.testapp.base.BaseTestActivity; + +/** Activity for testing dialogs created with MaterialAlertDialogBuilder. */ +public class MaterialAlertDialogActivity extends BaseTestActivity { + + @Override + protected int getContentViewLayoutResId() { + return R.layout.frame_layout; + } +} diff --git a/tests/javatests/com/google/android/material/dialog/MaterialAlertDialogImeTest.java b/tests/javatests/com/google/android/material/dialog/MaterialAlertDialogImeTest.java new file mode 100644 index 00000000000..a121699347a --- /dev/null +++ b/tests/javatests/com/google/android/material/dialog/MaterialAlertDialogImeTest.java @@ -0,0 +1,226 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.android.material.dialog; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +import android.os.SystemClock; +import android.view.View; +import android.view.Window; +import android.view.WindowInsets; +import android.view.WindowManager.LayoutParams; +import android.view.WindowMetrics; +import android.widget.EditText; +import android.widget.LinearLayout; +import androidx.appcompat.app.AlertDialog; +import androidx.core.view.WindowCompat; +import androidx.core.view.WindowInsetsCompat; +import androidx.test.filters.MediumTest; +import androidx.test.filters.SdkSuppress; +import androidx.test.rule.ActivityTestRule; +import androidx.test.runner.AndroidJUnit4; +import com.google.android.material.testapp.MaterialAlertDialogActivity; +import com.google.android.material.textfield.TextInputEditText; +import com.google.android.material.textfield.TextInputLayout; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Tests of the vertical background insets of a dialog created with {@link + * MaterialAlertDialogBuilder} while the soft keyboard is shown. + * + *

The tests need a soft keyboard and are skipped when none is shown. To make the dialog content + * conflict with the keyboard on any screen, the configured insets are a quarter of the window + * height each. The keyboard visibility is read from the window metrics, available on API 30+. + */ +@MediumTest +@RunWith(AndroidJUnit4.class) +@SdkSuppress(minSdkVersion = 30) +public class MaterialAlertDialogImeTest { + + private static final long KEYBOARD_TIMEOUT_MS = 5000; + private static final long SETTLE_TIMEOUT_MS = 5000; + private static final long QUIET_PERIOD_MS = 1000; + + @Rule + public final ActivityTestRule activityTestRule = + new ActivityTestRule<>(MaterialAlertDialogActivity.class); + + private final AtomicReference dialog = new AtomicReference<>(); + private final AtomicInteger decorLayouts = new AtomicInteger(); + + @After + public void dismissDialog() throws Throwable { + activityTestRule.runOnUiThread(() -> { + if (dialog.get() != null) { + dialog.get().dismiss(); + } + }); + } + + @Test + public void adjustResize_keyboardShown_textFieldIsNotCollapsed() throws Throwable { + EditText field = showDialogWithTextFields(1, LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + waitForKeyboard(); + waitUntilSettled(); + + assertTrue("text field collapsed", field.getHeight() > 0); + assertTrue("text field covered by the keyboard", bottomOnScreen(field) <= keyboardTop()); + } + + @Test + public void adjustPan_keyboardShown_dialogFitsAboveKeyboardAndSettles() throws Throwable { + EditText field = showDialogWithTextFields(2, LayoutParams.SOFT_INPUT_ADJUST_PAN); + waitForKeyboard(); + waitUntilSettled(); + + decorLayouts.set(0); + SystemClock.sleep(QUIET_PERIOD_MS); + assertEquals("dialog layout does not settle", 0, decorLayouts.get()); + assertTrue("text field collapsed", field.getHeight() > 0); + assertTrue( + "dialog covered by the keyboard", + bottomOnScreen(dialog.get().getWindow().getDecorView()) <= keyboardTop()); + } + + @Test + public void keyboardHidden_configuredInsetsAreRestored() throws Throwable { + showDialogWithTextFields(2, LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + waitForKeyboard(); + waitUntilSettled(); + View decorView = dialog.get().getWindow().getDecorView(); + int configuredPadding = configuredInset(); + assertTrue("insets not shrunk", decorView.getPaddingTop() < configuredPadding); + + activityTestRule.runOnUiThread(() -> + WindowCompat.getInsetsController(dialog.get().getWindow(), decorView) + .hide(WindowInsetsCompat.Type.ime())); + waitFor(() -> keyboardTop() == Integer.MAX_VALUE, KEYBOARD_TIMEOUT_MS, "keyboard not hidden"); + waitFor( + () -> decorView.getPaddingTop() == configuredPadding, + SETTLE_TIMEOUT_MS, + "insets not restored"); + } + + /** Shows a dialog with text fields and the keyboard; returns the first, focused field. */ + private EditText showDialogWithTextFields(int count, int softInputMode) throws Throwable { + AtomicReference first = new AtomicReference<>(); + activityTestRule.runOnUiThread(() -> { + MaterialAlertDialogActivity activity = activityTestRule.getActivity(); + LinearLayout content = new LinearLayout(activity); + content.setOrientation(LinearLayout.VERTICAL); + for (int i = 0; i < count; i++) { + TextInputLayout layout = new TextInputLayout(activity); + layout.setHint("Field " + (i + 1)); + TextInputEditText editText = new TextInputEditText(layout.getContext()); + layout.addView(editText); + content.addView(layout); + if (i == 0) { + first.set(editText); + } + } + int inset = configuredInset(); + AlertDialog alertDialog = + new MaterialAlertDialogBuilder(activity) + .setTitle("Title") + .setView(content) + .setPositiveButton("OK", null) + .setNegativeButton("Cancel", null) + .setBackgroundInsetTop(inset) + .setBackgroundInsetBottom(inset) + .create(); + Window window = alertDialog.getWindow(); + window.setSoftInputMode(softInputMode); + dialog.set(alertDialog); + alertDialog.show(); + window + .getDecorView() + .addOnLayoutChangeListener( + (v, l, t, r, b, oldL, oldT, oldR, oldB) -> decorLayouts.incrementAndGet()); + first.get().requestFocus(); + WindowCompat.getInsetsController(window, first.get()).show(WindowInsetsCompat.Type.ime()); + }); + return first.get(); + } + + private int configuredInset() { + return windowMetrics().getBounds().height() / 4; + } + + private void waitForKeyboard() { + long deadline = SystemClock.uptimeMillis() + KEYBOARD_TIMEOUT_MS; + while (keyboardTop() == Integer.MAX_VALUE && SystemClock.uptimeMillis() < deadline) { + SystemClock.sleep(50); + } + assumeTrue("no soft keyboard shown", keyboardTop() != Integer.MAX_VALUE); + } + + /** + * Waits until the dialog has not been laid out for a while. Does not wait for the main thread to + * become idle: a layout that does not settle would block such a wait forever. + */ + private void waitUntilSettled() { + long deadline = SystemClock.uptimeMillis() + SETTLE_TIMEOUT_MS; + int last = -1; + while (SystemClock.uptimeMillis() < deadline) { + int current = decorLayouts.get(); + if (current == last) { + return; + } + last = current; + SystemClock.sleep(300); + } + } + + /** Returns the top of the keyboard in screen coordinates, or MAX_VALUE without the keyboard. */ + private int keyboardTop() { + WindowMetrics metrics = windowMetrics(); + WindowInsets insets = metrics.getWindowInsets(); + if (!insets.isVisible(WindowInsets.Type.ime())) { + return Integer.MAX_VALUE; + } + return metrics.getBounds().bottom - insets.getInsets(WindowInsets.Type.ime()).bottom; + } + + private WindowMetrics windowMetrics() { + return activityTestRule.getActivity().getWindowManager().getCurrentWindowMetrics(); + } + + private static int bottomOnScreen(View view) { + int[] location = new int[2]; + view.getLocationOnScreen(location); + return location[1] + view.getHeight(); + } + + private static void waitFor(Condition condition, long timeoutMs, String message) { + long deadline = SystemClock.uptimeMillis() + timeoutMs; + while (!condition.isMet() && SystemClock.uptimeMillis() < deadline) { + SystemClock.sleep(50); + } + assertTrue(message, condition.isMet()); + } + + private interface Condition { + boolean isMet(); + } +}