UiAutomator for android 巧換角度

本文章主要描述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.其他
寫此文,僅爲和大家相互學習,如果有牛大大,請多多指點,歡迎私聊,勿口水戰.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章