Java+Uiautomator -- Uiobject 判断一个元素是否存在?waitForExists()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ricky_yangrui/article/details/89221257

今天写代码的时候,搜索一个文件,我需要判断搜索的文件是否存在,Python中我会,但是Java的uiautomator不太熟悉,找了下网上的教程,怎么都是把API罗列出来的,知道waitForExists(),但是我不知道怎么用啊,无奈只好自己去看源码:

/**
 * Waits a specified length of time for a view to become visible.
 *
 * This method waits until the view becomes visible on the display, or
 * until the timeout has elapsed. You can use this method in situations where
 * the content that you want to select is not immediately displayed.
 *
 * @param timeout the amount of time to wait (in milliseconds)
 * @return true if the view is displayed, else false if timeout elapsed while waiting
 * @since API Level 16
 */
public boolean waitForExists(long timeout) {
    Tracer.trace(timeout);
    if(findAccessibilityNodeInfo(timeout) != null) {
        return true;
    }
    return false;
}

找到之后,还是没例子,机制如我

果然能够跳转,跳转过去,就发现了源码上有例子:

public void legacySetText(String text) throws UiObjectNotFoundException {
    Tracer.trace();
    // long click left + center
    AccessibilityNodeInfo node = findAccessibilityNodeInfo(mConfig.getWaitForSelectorTimeout());
    if (node == null) {
        throw new UiObjectNotFoundException(getSelector().toString());
    }
    Rect rect = getVisibleBounds(node);
    getInteractionController().longTapNoSync(rect.left + 20, rect.centerY());
    // check if the edit menu is open
    UiObject selectAll = new UiObject(new UiSelector().descriptionContains("Select all"));
    if (selectAll.waitForExists(50)) {
        selectAll.click();
    }
    // wait for the selection
    SystemClock.sleep(250);
    // delete it
    getInteractionController().sendKey(KeyEvent.KEYCODE_DEL, 0);

    // Send new text
    getInteractionController().sendText(text);
}

然后其中的这句就是我想要的:

    UiObject selectAll = new UiObject(new UiSelector().descriptionContains("Select all"));
if (selectAll.waitForExists(50)) {
    selectAll.click();
}

然后自己就可以写一个啦:

猜你喜欢

转载自blog.csdn.net/ricky_yangrui/article/details/89221257