espresso 元素遮挡问题。

在使用espresso进行测试的时候,点击一个横向列表的时候会在点击的项目下出现对应的横线。

实现方式是在FrameLayout下放两个TextView,

一个TextView包含下划线,默认是FrameLayout的第一个元素;

一个TextView不包含下划线,默认是FrameLayout的第二个元素;

两个元素大小一致,当选中时,切换1,2两个TextView的属性。

 

espresso使用的matcher为:

  

Matcher<View> viewLabel = allOf(withClassName(endsWith("TextView")), isNotCoveredByBothers(), withAlpha(1.0f), isDisplayed(), isDescendantOfA(withId(TABS)));

TABS是列表的祖先元素。
查看代码发现 两个TextView 区别就是 Alpha 值不一样,有下划线的 Alpha 值为1.0.(设置这个值为什么会有这样的下划线)。

    /**
     * isNotCoveredByBothers
     * @return
     */
    public static Matcher<View> isNotCoveredByBothers() {
        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("is displayed on the screen to the user");
            }

            @Override
            public boolean matchesSafely(View view) {
                return view.getGlobalVisibleRect(new Rect())
                        && !isViewCoveredBybrothers(view);
            }
        };
    }

    /**
     * 检查一个包含父控件的view是否被后面的兄弟遮挡
     * 检查一个包含父控件的view是否被后面的兄弟遮挡
     * @param view
     * @return
     */
    public static boolean isViewCoveredBybrothers(final View view) {
        View currentView = view;
        if  (currentView.getParent() == null) {
            //无父控件,当作未遮挡
            return false;
        }
        if (currentView.getParent() instanceof ViewGroup) {
            ViewGroup currentParent = (ViewGroup) currentView.getParent();
            // if the parent of view is not visible,return true
            if (currentParent.getVisibility() != View.VISIBLE) {
                //父控件不可见
                return true;
            }

            int start = indexOfViewInParent(currentView, currentParent);
            for (int i = start + 1; i < currentParent.getChildCount(); i++) {
                Rect viewRect = new Rect();
                view.getGlobalVisibleRect(viewRect);
                View otherView = currentParent.getChildAt(i);
                Rect otherViewRect = new Rect();
                otherView.getGlobalVisibleRect(otherViewRect);
                // if view intersects its older brother(covered),return true
                if (Rect.intersects(viewRect, otherViewRect)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * view在parent的index
     * @param view
     * @param parent
     * @return
     */
    private static int indexOfViewInParent(View view, ViewGroup parent) {
        int index;
        for (index = 0; index < parent.getChildCount(); index++) {
            if (parent.getChildAt(index) == view) {
                break;
            }
        }
        return index;
    }

 

posted on 2017-10-18 09:42  假的程序员  阅读(285)  评论(0编辑  收藏  举报

导航