以下是对代码的详细解释:
xxxxxxxxxx
/**
* 安全点击控件(兼容可点击与不可点击控件)
* @param {UiObject} widget - 目标控件对象
*/
function safeClick(widget) {
if (widget.clickable()) {
widget.click(); // 可点击控件直接调用click()
} else {
// 不可点击控件通过中心坐标点击
let bounds = widget.bounds();
click(bounds.centerX(), bounds.centerY());
}
sleep(1000); // 等待操作生效
}
/**
* 查找控件并在文本匹配时点击
* @param {UiSelector} selector - 控件选择器
* @param {string} targetText - 目标匹配文本
* @returns {boolean} 匹配并点击成功返回true,否则返回false
*/
function findAndClickIfMatch(selector, targetText) {
// 查找控件(超时5秒)
let widget = selector.findOne(5000);
if (!widget) {
toast("未找到控件");
return false;
}
// 获取控件文本(优先text,其次desc)
let widgetText = widget.text() || widget.desc();
console.log("控件文本:", widgetText);
// 文本匹配时执行点击
if (widgetText === targetText) {
console.log("文本匹配,尝试点击");
safeClick(widget);
return true;
} else {
console.log("文本不匹配");
return false;
}
}
/**
* 微信搜索并点击目标联系人主流程
* @param {string} targetName - 目标联系人名称
*/
function searchAndClickContact(targetName) {
// 点击搜索栏
let searchEntry = id("jha").findOne();
if (searchEntry) {
searchEntry.click();
sleep(2000);
} else {
toast("未找到微信搜索栏");
exit();
}
// 在搜索框输入目标名称
let inputBox = className("EditText").findOne();
if (inputBox) {
inputBox.setText(targetName);
sleep(2000); // 等待搜索结果加载
} else {
toast("未找到搜索输入框");
exit();
}
sleep(1500);
// 查找并点击匹配的联系人
findAndClickIfMatch(id("odf"), targetName);
// (可选)滚动查找逻辑(默认注释,按需启用)
// for (let i = 0; i < 5; i++) {
// if (findAndClickIfMatch(id("odf"), targetName)) break;
// scrollDown(); // 向下滚动
// sleep(1500);
// }
}
// 执行主流程:搜索并点击"昵称"
searchAndClickContact("昵称");