uiautomator中UiObject中getChildCount和getChild方法解惑

问题描述


getChildCount得到的子节点数是当前节点的下一层的控件数,不包括子节点的子节点。但是用getChild(UiSelector)中遍历控件的时候,把当前节点的子子孙孙全部遍历一遍。那我就想遍历当前节点的子节点,怎么办?可以传ClassName进去进行筛选,但是有可能其他手机的每一列并不是又linearLayout来布局的。所以最好的方法,是一instance遍历。忽略它是那种className,直接以编号获得。


实战


我要遍历下面图片所示的界面里的列表里的元素,挨个点击。




public void test_DesktopEffects() throws UiObjectNotFoundException {
		uiDevice = getUiDevice();
		width = uiDevice.getDisplayWidth();
		height = uiDevice.getDisplayHeight();
		enterMenu(uiDevice, ValueUtil.DESKTOPEFFECT);

		UiScrollable list = UiUtil.findScrollableByClass(WidgetUtil.LISTVIEW);
		int count = list.getChildCount();
		Log.i(TAG, "count: " + count);
		for (int i = 0; i < count; i++) {
			UiObject child = list.getChild(new UiSelector().instance(i));
			Log.i(TAG, "i: " + i + ", " + child.getBounds().toString());
			child.clickAndWaitForNewWindow();
			uiDevice.pressHome();
			Random random = new Random();
			// 测试时使用1次循环,正式使用时,改为10次
			for (int j = 0; j < 1; j++) {

				int index = random.nextInt(2);
				if (index == 0) {
					uiDevice.swipe(width - 48, height / 2, 48, height / 2, 10);
				} else {
					uiDevice.swipe(48, height / 2, width - 48, height / 2, 10);
				}
			}
			if (i < count - 1) {
				enterMenu(uiDevice, ValueUtil.DESKTOPEFFECT);
			}
		}
		uiDevice.pressHome();
	}

打印的log:


04-19 14:48:45.622: I/Idle(5001): count: 7
04-19 14:48:46.162: I/Idle(5001): i: 0, Rect(38, 210 - 502, 306)
04-19 14:48:52.288: I/Idle(5001): i: 1, Rect(62, 230 - 397, 285)
04-19 14:48:58.795: I/Idle(5001): i: 2, Rect(62, 239 - 197, 276)
04-19 14:49:05.731: I/Idle(5001): i: 3, Rect(397, 210 - 487, 306)
04-19 14:49:14.029: I/Idle(5001): i: 4, Rect(397, 210 - 487, 306)
04-19 14:49:20.276: I/Idle(5001): i: 5, Rect(397, 210 - 487, 306)
04-19 14:49:26.572: I/Idle(5001): i: 6, Rect(38, 307 - 502, 403)

从log可以看出,程序遍历了第一个子元素下面的子元素。且从脚本运行结果来看,都没有完全遍历所有子元素。虽然getChildCount得到了数量,但是真正的对象我们却无法得到,所以很疑惑google设计初衷。


修改一些代码叫获取元素的方法改为如下:


UiObject child = list.getChild(new UiSelector().clickable(true).instance(i));


运行程序打印Log:


04-19 15:46:53.485: I/Idle(6648): count: 7
04-19 15:46:54.025: I/Idle(6648): i: 0, Rect(38, 210 - 502, 306)
04-19 15:46:59.711: I/Idle(6648): i: 1, Rect(38, 307 - 502, 403)
04-19 15:47:06.417: I/Idle(6648): i: 2, Rect(38, 404 - 502, 500)
04-19 15:47:14.535: I/Idle(6648): i: 3, Rect(38, 501 - 502, 597)
04-19 15:47:21.172: I/Idle(6648): i: 4, Rect(38, 598 - 502, 694)
04-19 15:47:29.790: I/Idle(6648): i: 5, Rect(38, 695 - 502, 791)
04-19 15:47:36.256: I/Idle(6648): i: 6, Rect(38, 792 - 502, 888)

现在点击的点才是正确的。加一个clickable(true),而且控件可点击在每一个listview里的每一个元素都必须要可点击。而且google也要求相互重叠的元素可点击是唯一的。这样才能好确认焦点。所以这个问题就算解决了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值