这是我的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" /
因为我使用app:layout_constraintEnd_toEndOf="@+id/loginTextView"
和app:layout_constraintStart_toStartOf="@+id/loginTextView"
registerTextView
是水平居中的。
现在我想写Espresso测试检查 registerTextView 是否水平居中? 我怎么能这样做?
答案 0 :(得分:1)
您所要做的就是检索显示尺寸并确保视图的左坐标等于右视图坐标和右显示坐标之间的距离。所以,你可以创建一个匹配器:
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) {
}
};
}
然后将其用作:
onView(withId(R.id.registerTextView)).check(matches(isCenteredHorizontally()));