Android-Espresso:如何检查 TextView 水平居中?

Android-Espresso: How check TextView is center horizontally?

这是我的 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 是否在水平中心? 我该怎么做?

您所要做的就是检索显示尺寸并确保视图的左坐标等于右视图坐标与右显示坐标之间的距离。所以,你可以创建一个像这样的匹配器:

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()));