Merge cherrypicks of [13475365, 13475021] into mainline-release

Change-Id: I6d12c9c28a0aee2258819d395e5ac02ef7a46872
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
index 4c99693..2e785f5 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
@@ -21,6 +21,7 @@
 import android.content.Intent;
 import android.content.IntentSender;
 import android.database.Cursor;
+import android.graphics.Rect;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.SystemClock;
@@ -118,8 +119,18 @@
         // Repeat swipe gesture to find our item
         // (UiScrollable#scrollIntoView does not seem to work well with SwipeRefreshLayout)
         UiObject targetObject = new UiObject(docList.childSelector(new UiSelector().text(label)));
+        UiObject saveButton = findSaveButton();
         int stepLimit = 10;
-        while (!targetObject.exists() && stepLimit-- > 0) {
+        while (stepLimit-- > 0) {
+            if (targetObject.exists()) {
+                boolean targetObjectFullyVisible = !saveButton.exists()
+                        || targetObject.getVisibleBounds().bottom
+                        <= saveButton.getVisibleBounds().top;
+                if (targetObjectFullyVisible) {
+                    break;
+                }
+            }
+
             mDevice.swipe(/* startX= */ mDevice.getDisplayWidth() / 2,
                     /* startY= */ mDevice.getDisplayHeight() / 2,
                     /* endX= */ mDevice.getDisplayWidth() / 2,