摘要
GetAttribute 实际上从字面上我们就能够明白,它是获取元素的一些属性。类似于文本内容,类名,resourId等。当然还包括了一些属性状态,如clickable,checkable等等,
正文
GetAttribute的代码其实挺简单的 我们来看下吧
public AndroidCommandResult execute(final AndroidCommand command)
throws JSONException {
if (command.isElementCommand()) {
// only makes sense on an element
final Hashtable<String, Object> params = command.params();
try {
final AndroidElement el = command.getElement();
final String attr = params.get("attribute").toString();
if (attr.equals("name") || attr.equals("text")
|| attr.equals("className") || attr.equals("resourceId")) {
return getSuccessResult(el.getStringAttribute(attr));
} else {
return getSuccessResult(String.valueOf(el.getBoolAttribute(attr)));
}
} catch (final NoAttributeFoundException e) {
return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
e.getMessage());
} catch (final UiObjectNotFoundException e) {
return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
e.getMessage());
} catch (final Exception e) { // el is null
return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
e.getMessage());
}
} else {
return getErrorResult("Unable to get attribute without an element.");
}
}
前面的部分就没什么好说的,都是一样的,获取到一个AndroidElement的对象,它这里处理的话主要分为两种
- 字符串类型的属性,如text、name、className、resourceId 这里面的name实际上就相当于我们在Uiautomator里面的cont-desc ,但是name呢 有个小坑,我们等下下面会提到
- bool类型的属性,这里就比较多了类似于 clickable,checkable,等等
区别以上两种 情况当然就做两种处理啦 我们看下getStringAttribute 方法
public String getStringAttribute(final String attr)
throws UiObjectNotFoundException, NoAttributeFoundException {
String res;
if (attr.equals("name")) {
res = getContentDesc();
if (res.equals("")) {
res = getText();
}
} else if (attr.equals("text")) {
res = getText();
} else if (attr.equals("className")) {
res = getClassName();
} else if (attr.equals("resourceId")) {
res = getResourceId();
} else {
throw new NoAttributeFoundException(attr);
}
return res;
}
以上的代码最后都是调用UIAutomator的,所以没什么好说的,但是这里需要说下name,
首先它会获取contentDesc的内容,如果是空的话,它又会去获取文本的内容,所以说如果你通过getAttribute去获取contentDes的话,并且contentDes是空的情况下,它会返回给你文本的内容,所以这个地方要注意一下。
再来就是getBoolAttribute
public boolean getBoolAttribute(final String attr)
throws UiObjectNotFoundException, NoAttributeFoundException {
boolean res;
if (attr.equals("enabled")) {
res = el.isEnabled();
} else if (attr.equals("checkable")) {
res = el.isCheckable();
} else if (attr.equals("checked")) {
res = el.isChecked();
} else if (attr.equals("clickable")) {
res = el.isClickable();
} else if (attr.equals("focusable")) {
res = el.isFocusable();
} else if (attr.equals("focused")) {
res = el.isFocused();
} else if (attr.equals("longClickable")) {
res = el.isLongClickable();
} else if (attr.equals("scrollable")) {
res = el.isScrollable();
} else if (attr.equals("selected")) {
res = el.isSelected();
} else if (attr.equals("displayed")) {
res = el.exists();
} else {
throw new NoAttributeFoundException(attr);
}
return res;
}
上面的代码就不说了,需要说一点的是,这里获取不到UiAutomator属性里面的password,package,index 这三个属性,主要是appium没有实现这几个的接口,如果有的话,可能也是能够拿的到的。