Issue
Here my xml:
<TextView
android:id="@+id/loginTextView"
android:layout_width="255dp"
android:layout_height="60dp"
android:layout_marginBottom="15dp"
android:background="@drawable/sign_in_login_bg"
android:gravity="center"
android:onClick="@{ () -> presenter.doLogin()}"
android:text="@string/login"
android:textAllCaps="true"
android:textColor="@android:color/white"
app:layout_constraintBottom_toTopOf="@+id/registerTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/registerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:onClick="@{ () -> presenter.doRegister()}"
android:text="@string/register"
android:textAllCaps="true"
android:textColor="@color/color_primary"
android:textSize="13sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/forgotPasswordTextView"
app:layout_constraintEnd_toEndOf="@+id/loginTextView"
app:layout_constraintStart_toStartOf="@+id/loginTextView" /
Because I use app:layout_constraintEnd_toEndOf="@+id/loginTextView"
and app:layout_constraintStart_toStartOf="@+id/loginTextView"
the registerTextView
is center horizontally.
And now I want to write Espresso test check that registerTextView is on center horizontally? How I can do this?
Solution
All you have to do is to retrieve the display size and make sure the left coordinate of the view equals to the distance between a right view coordinate and a right display one. So, you could create a matcher like:
private static Matcher<View> isCenteredHorizontally() {
return new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View item) {
WindowManager windowManager = (WindowManager) item.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width = displaySize.x + 1;
int[] outLocation = new int[2];
item.getLocationOnScreen(outLocation);
int viewLeft = outLocation[0];
int rightMargin = width - (viewLeft + item.getMeasuredWidth());
// if screen width is an even number and view width an odd one then an error is 1 point
return Math.abs(rightMargin - viewLeft) < 2;
}
@Override
public void describeTo(Description description) {
}
};
}
And then use it as:
onView(withId(R.id.registerTextView)).check(matches(isCenteredHorizontally()));
Answered By - Anatolii
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.