可能有人会问,robotium自带了waitForText(String text)方法为何还需要自己写,首先看其最终执行的代码片段如下:
1 | if (scroll && !scroller.scrollDown()){ |
2 | logMatchesFound(regex); |
6 | logMatchesFound(regex); |
我们知道方法在执行的时候会首先在当前界面查找控件,但是当前界面未找到指定view的时候则会调用solo.scrollDown()方法,但在实际自动化编码过程中会发现上面的方法并不一定完全适合自己。
查看solo.scrollDown()最终的代码:
02 | * Scrolls up and down. |
04 | * @param direction the direction in which to scroll |
05 | * @param allTheWay <code>true</code> if the view should be scrolled to the beginning or end, |
06 | * <code>false</code> to scroll one page up or down. |
07 | * @return {@code true} if more scrolling can be done |
10 | public boolean scroll( int direction, boolean allTheWay) { |
12 | final ArrayList viewList = RobotiumUtils. |
13 | removeInvisibleViews(viewFetcher.getAllViews( true )); |
14 | @SuppressWarnings ( "unchecked" ) |
15 | ArrayList views = RobotiumUtils.filterViewsToSet( new Class[] { ListView. class , |
16 | ScrollView. class , GridView. class , WebView. class }, viewList); |
17 | View view = viewFetcher.getFreshestView(views); |
24 | if (view instanceof AbsListView) { |
25 | return scrollList((AbsListView)view, direction, allTheWay); |
28 | if (view instanceof ScrollView) { |
30 | scrollScrollViewAllTheWay((ScrollView) view, direction); |
33 | return scrollScrollView((ScrollView)view, direction); |
36 | if (view instanceof WebView){ |
37 | return scrollWebView((WebView)view, direction, allTheWay); |
上面代码以要拖动的为listview为例,假如拖动的界面是listview那么则会调用下面的代码片段:
1 | if (view instanceof AbsListView) { |
2 | return scrollList((AbsListView)view, direction, allTheWay); |
有兴趣可以继续追scrollList的实现(其实就是view.setSelection(lineToMoveTo)),那么每次拖动多少距离呢,从这里可以看出实际上模拟拖动的距离是和listview的item的高度有关,因此引出下面我们要自定义waitforText()方法的原因;下面是我画的一张图:
可以点击放大查看,主要描述的意思是当listview的第一个item的高度超过一屏,而且item中又存在多个控件,要查找字符串为“robotium中文网”的控件,且实际是在屏幕外面的,并且在实际的软件界面可能没有加载进来,如果用robotium的solo.waitForText(“robotium中文网”)方法执行查找时,流程为首先在当前界面查找,未找到则执行scrollDown()向下滚动,假如我认为最小只滚动1行的距离,那么出现的可能原因是要查找的显示为”robotium中文网”的view从屏幕下方外滚动到屏幕上方外,此时再执行当前界面查找时也不会找到该控件,因此出现明明有这个控件但是solo.waitForText()无法找到的情况。我们没必要从头写,直接借鉴和结合robotium即可:
06 | public static boolean waitForText(Solo solo, String text){ |
07 | final long endTime = SystemClock.uptimeMillis() + TIMEOUT; |
08 | boolean foundAnyMatchingView = false ; |
10 | while (SystemClock.uptimeMillis() < endTime) { |
11 | foundAnyMatchingView = solo.waitForText(text, 0 , 1 , false ); |
12 | if (foundAnyMatchingView){ |
15 | scrollVertical(solo, y); |
17 | return foundAnyMatchingView; |
scrollVertical(solo, y)方法是如何来的呢,请移步:http://www.robotium.cn/archives/1323
若有错误,欢迎指正!