diff --git a/espresso/core/java/androidx/test/espresso/matcher/ViewMatchers.java b/espresso/core/java/androidx/test/espresso/matcher/ViewMatchers.java index c6fc43588..40e837649 100644 --- a/espresso/core/java/androidx/test/espresso/matcher/ViewMatchers.java +++ b/espresso/core/java/androidx/test/espresso/matcher/ViewMatchers.java @@ -128,6 +128,11 @@ public static Matcher isFocusable() { return new IsFocusableMatcher(); } + /** Returns a matcher that matches {@link View Views} that are focused. */ + public static Matcher isFocused() { + return new IsFocusedMatcher(); + } + /** Returns a matcher that matches {@link View Views} currently have focus. */ public static Matcher hasFocus() { return new HasFocusMatcher(); @@ -901,6 +906,21 @@ public boolean matchesSafely(View view) { } } + static final class IsFocusedMatcher extends TypeSafeMatcher { + @RemoteMsgConstructor + private IsFocusedMatcher() {} + + @Override + public void describeTo(Description description) { + description.appendText("is focused"); + } + + @Override + public boolean matchesSafely(View view) { + return view.isFocused(); + } + } + static final class HasFocusMatcher extends TypeSafeMatcher { @RemoteMsgConstructor private HasFocusMatcher() {} diff --git a/espresso/core/javatests/androidx/test/espresso/matcher/ViewMatchersTest.java b/espresso/core/javatests/androidx/test/espresso/matcher/ViewMatchersTest.java index 91a432e64..ba5b4fe80 100644 --- a/espresso/core/javatests/androidx/test/espresso/matcher/ViewMatchersTest.java +++ b/espresso/core/javatests/androidx/test/espresso/matcher/ViewMatchersTest.java @@ -34,6 +34,7 @@ import static androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isFocusable; +import static androidx.test.espresso.matcher.ViewMatchers.isFocused; import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; import static androidx.test.espresso.matcher.ViewMatchers.isSelected; @@ -495,6 +496,18 @@ public void isFocusableTest() { assertFalse(isFocusable().matches(notFocusable)); } + @Test + public void isFocusedTest() { + View focused = new View(context); + focused.setFocusable(true); + focused.setFocusableInTouchMode(true); + focused.requestFocus(); + View notFocused = new View(context); + assertTrue(focused.isFocused()); + assertTrue(isFocused().matches(focused)); + assertFalse(isFocused().matches(notFocused)); + } + @Test public void isSelectedTest() { View selected = new View(context);