Android 如何判断一个View在屏幕上可见

自动化测试中,遇到一个问题。

由于存在多个View覆盖,有什么方法,
能判断哪个或哪些View在屏幕上可见,并将屏幕不可见的view过滤掉。

我曾采用

view.hasWindowFocus() && view.getVisibility() == View.VISIBLE && view.isShown()

但这三个条件都不能很好的解决, 即使某个view在下层,屏幕上不可见,但依然能通过我的判断条件。

求帮助。

阅读 30.8k
3 个回答

就算View被别的View挡住了,也是有可能获取到点击事件或者说被用户看到的。所以这不是根本解决之道。不知道你是想测什么东西。为何要把没有显示在最上层的View给过滤掉

处于什么目的呢

`private boolean isViewVisible(View host, Rect window, boolean fullVisible) {

// Make sure our host view is attached to a visible window.

if (host.getWindowVisibility() == View.VISIBLE) {

    // An invisible predecessor or one with alpha zero means

// that this view is not visible to the user. Object current = host;
while (current instanceof View) {

        View view = (View) current;

// We have attach info so this view is attached and there is no
// need to check whether we reach to ViewRootImpl on the way up. if (view.getAlpha() <= 0 || view.getVisibility() != View.VISIBLE) {

            return false;

}

        current = view.getParent();

}

    // Check if the view is visible in window.

// host.getWindowVisibleDisplayFrame(mWindowRect); Rect visibleRect = new Rect();
if (fullVisible) {

        // Check if the view is entirely visible.

if (!host.getLocalVisibleRect(visibleRect)) {

            return false;

}

        return visibleRect.top == 0 && visibleRect.left == 0 &&
                visibleRect.bottom == host.getHeight() && visibleRect.right == host.getWidth();

} else {

        // Check if the view is entirely covered by its predecessors.

if (!host.getGlobalVisibleRect(visibleRect)) {

            return false;

}

        return Rect.intersects(window, visibleRect);

}

}
return false;`
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题