UiAutomator for android 巧换角度

来源:互联网 发布:cf卡装备软件 编辑:程序博客网 时间:2024/05/14 18:05

本文章主要描述UIAutomator测试中遇到子节点无法寻觅到父节点的问题
1. 问题描叙
我在一个示例项目中引用到了UIAutomator测试,在一个动态listView中,要点击5:00下的item选项,并且其中的test都是动态生成的(即不可用text属性获取控件),且无desc属性。为了适应多种分辨率坐标属性也不可用(系统获取除外)。要分别点击到图片,和内容。

图1

二图是一个布局示意图:
图2

2.常规思路
一般遇到这种问题,我的的常规想法,是事先通过.text(“5:00”)来获取此对象object(图中深色区域),然后通过object.getFromParent(selector)来获取父亲布局对象,再向上寻根得到最外的布局maxfatherObject,再由在外的父节点向下搜索,到满足条件的子孙节点。maxfatherObject.getChild(selector),事实上由于是自定义的模板,Id都是复用的,失去唯一性。另外还可能其他时间线也可能存在item,所以最大布局的index不能作为确定的参数。

 1.         UiScrollable mtime = new UiScrollable(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_item_tv_time_value").text("5:00")); 2. UiObject father = mtime.getFromParent(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_item_title_panel")); 3. UiObject maFather = father.getFromParent(new UiSelector().className("android.widget.RelativeLayout")); 4.         UiObject sonlay = mafather.getChild(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_item_content_panel").index(1)); 5. sonlay.click(); 

第3行代码仅依靠classname是无法定位当前对象的,系统会默认为listView的第一个index=0的布局,这样造成的结果是,系统报错not found exception.

3.另寻它径
我们可以通过 .scrollIntoView(object); 从list中找到时间线,然后拖到ListView最上边,这可以通过rect来系统获取list在屏幕中的四个顶点的坐标,即只需要包时间线的Y坐标和list顶点坐标一致即可,然后就可以通过id来定位到具体控件了,如果一个时间线上存在多个在窗口内的item,我们就可以用classname结合instance(或index)来定位,再找到相应的子控件了,在这就不一一讨论了.

下面是具体代码:

public void testfindItem() throws UiObjectNotFoundException{        UiScrollable scroll =new UiScrollable(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_content_list"));        UiObject mtime = new UiObject(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_item_tv_time_value").text("6:00"));        scroll.scrollIntoView(mtime);        sleep(4000);        Rect lr=scroll.getVisibleBounds();        //Rect(int left,int top,int right,int bottom;        int x1 = lr.left;        int y1 = lr.top;        head.dragTo(x1+1, y1, 80) ;                    System.out.println("默认最大滚动次数:"+scroll.getMaxSearchSwipes());        sleep(3000);        UiObject pic = new UiObject(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_workorder_item_layout_iv_image"));           UiObject content = new UiObject(new UiSelector().resourceId("com.starlight.mobile.android.ama:id/calendar_day_time_workorder_item_layout_rl_content"));        pic.click();        sleep(5000);        UiDevice.getInstance().pressBack();        sleep(5000);        content.clickAndWaitForNewWindow();        sleep(5000);

3.其他
写此文,仅为和大家相互学习,如果有牛大大,请多多指点,欢迎私聊,勿口水战.

0 0