本人在使用UiAutomator作测试的时候,遇到一些控件须要长按一下子,好比录音功能,须要按住几秒,官方api不太好用,因此本身写了一个长按的方法。分享以下,供你们参考。java
/* * 根据resourceid获取控件并长按 * / public void longclickUiObectByResourceId(String id) throws UiObjectNotFoundException { int x = getUiObjectByResourceId(id).getBounds().centerX(); int y = getUiObjectByResourceId(id).getBounds().centerY(); UiDevice.getInstance().swipe(x, y, x, y, 300);//最后一个参数单位是5ms } /* * 根据文本获取控件并长按 * / public void longclickUiObectByText(String text) throws UiObjectNotFoundException { int x = getUiObjectByText(text).getBounds().centerX(); int y = getUiObjectByText(text).getBounds().centerY(); UiDevice.getInstance().swipe(x, y, x, y, 300);//最后一个参数单位是5ms } /* * 根据坐标并长按 * / public void longclickUiObectByText(int x, int y) throws UiObjectNotFoundException { UiDevice.getInstance().swipe(x, y, x, y, 300);//最后一个参数单位是5ms }
文章写做时间较早了,UiAutomator1基础的API进行封装的,还能够封装几个根据classname、index、或者description均可以,这里就不一一写了,最重要的最后一个,不经常使用可是颇有用,根据坐标点进行长按。还有一个根据坐标的数组进行轨迹的描绘,请参考android uiautomator一个画心形图案的方法--代码的浪漫android