Autox.js 控件操作方法 click setText scroll 对匹配到的控件做什么
找到控件了,然后呢
选择器帮你定位到了目标控件(一个 AccessibilityNodeInfo 对象),接下来就是对它发送动作。
点击类操作
let btn = text("确定").findOne();
// 语义点击——向控件发送一个 click 的 accessibility action
btn.click();
// 长按
btn.longClick();
// 双击(某些版本支持)
btn.doubleClick();
click() 和你用手指点屏幕不是一回事——它是通过无障碍服务向控件发送一个 "click" 事件。这意味着:
- 不依赖坐标——和你的手指在什么位置无关
- 不需要可视区域——控件即使被其他元素遮挡(部分遮挡),语义点击仍然能生效
- 大部分 App 能响应——但某些游戏(自绘 UI)不会响应无障碍事件,这时候就得换坐标操作或图像识别
文本操作
let input = className("EditText").findOne();
// 清空并填入
input.setText("新内容");
// 追加
input.append("更多文字");
// 读取当前值
console.log(input.text());
setText() 比模拟键盘输入更高效——它直接通过无障碍 API 设置文本,不需要逐个按键。
滚动操作
对于 ScrollView、RecyclerView、ListView 这类可滚动容器:
let list = className("RecyclerView").findOne();
// 向下滚(内容向上移)
list.scrollForward();
list.scrollDown();
// 向上滚(内容向下移)
list.scrollBackward();
list.scrollUp();
// 滚动到指定方向(Android API level 33+)
list.scroll(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
坐标操作 vs 语义点击
有时你需要拿到控件的屏幕坐标,然后用坐标点击:
let btn = text("确定").findOne();
let b = btn.bounds();
// b = { left: 100, top: 500, right: 200, bottom: 580 }
// 取中心点
let x = (b.left + b.right) / 2;
let y = (b.top + b.bottom) / 2;
// 用坐标点击(需要 Root 或无障碍坐标操作)
click(x, y);
为什么要绕这一圈?当语义点击不生效时(比如某些游戏、某些自定义 View),坐标点击反而能成功。但代价是绑死了屏幕分辨率——换台设备就错位。
常用属性读取
let c = className("Button").text("确定").findOne();
// 是否可点击
console.log(c.clickable());
// 是否启用
console.log(c.enabled());
// 是否选中
console.log(c.selected());
// 是否可聚焦
console.log(c.focusable());
// 层级深度
console.log(c.depth());
// 所属窗口 id
console.log(c.windowId());
// 父控件
console.log(c.parent().text());
// 子控件数量
console.log(c.childCount());
遍历控件树
let root = auto.getWindowRoot();
// 遍历所有控件
root.find().forEach(node => {
console.log(node.className() + " | " + node.text());
});
// 只查找可见的
root.find().filter(node => node.visibleToUser());
这招在你不确定屏幕上有什么的时候特别有用——调试神器。
等待与超时
Autox.js 的选择器 API 自带自动等待机制:
// findOne 默认会一直等直到控件出现(不推荐,可能死等)
text("欢迎").findOne();
// 等最多 5 秒,超时返回 null
text("欢迎").findOne(5000);
// until 也能指定超时
text("欢迎").until(5000);
推荐始终指定超时时间——无限等待在脚本逻辑错误时会让脚本卡死。
实战:自动填表脚本
console.show();
try {
// 打开设置页
launch("com.android.settings");
// 等待设置首页
if (!text("设置").findOne(10000)) {
throw new Error("设置页没打开");
}
// 搜索
let searchBtn = textContains("搜索").classNameContains("Button").findOne();
if (searchBtn) {
searchBtn.click();
sleep(500);
let input = className("EditText").findOne();
input.setText("电池");
sleep(1000);
// 点击搜索结果
text("电池").findOne(5000).click();
}
} catch (e) {
console.error("出错了:" + e.message);
}
什么时候换方案
| 情况 | 推荐方案 |
|---|---|
| 找到控件但 click() 没反应 | 改用坐标点击 click(bounds().centerX(), bounds().centerY()) |
| 找不到控件 | 用布局分析器重新核实属性 |
| 整个页面是自绘的(游戏) | 放弃选择器,用图像识别模块 |