天天看點

robotium源碼分析 ClickView

轉:http://blog.csdn.net/zqilu/article/details/17096201

public void clickOnScreen(float x, float y) {
       boolean successfull = false;
       Instrumentation inst;
       int retry = 0;
       while(!successfull && retry < 10) {
            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();
            MotionEvent event = MotionEvent.obtain(downTime, eventTime,MotionEvent.ACTION_DOWN, x, y, 0);
            MotionEvent event2 = MotionEvent.obtain(downTime, eventTime,MotionEvent.ACTION_UP, x, y, 0);
            try{
                  inst.sendPointerSync(event);
                  inst.sendPointerSync(event2);
                  successfull = true;
                  sleeper.sleep(MINISLEEP);
           }catch(SecurityException e){
                  dialogUtils.hideSoftKeyboard(null, false, true);
                  retry++;
           } 
       }
       if(!successfull) {
            Assert.assertTrue("Click can not be completed!", false);
      }
}
           

robotium關于Click的方法有 ClickOnView()、ClickLongOnView()、ClickInList()、ClickonSceen()clickOnActionBarItem()這幾個大類。

而ClickonScreen(float x,float y)源碼為:

      通過源碼我們知道Robotium點選View就是調用Instrumentation類方法中的sendPointSync(event)(模拟滑鼠點選),而clickOnView則是通過view的id或者index擷取到View,然後通過View的getLocationOnScreen()方法和View的寬和高得到該View的坐标,然後調用clickOnScreen()方法。View坐标擷取的代碼為:

view.getLocationOnScreen(xy);
final int viewWidth = view.getWidth();
final int viewHeight = view.getHeight();
final float x = xy[0] + (viewWidth / 2.0f);
float y = xy[1] + (viewHeight / 2.0f);
           

clickLongOnView則是在兩個event之間加上間隔時間。

clickOnActionBarItem()則是調用Instrumentation類方法中的invokeMenuActionSync(Activity activity,int id);方法。

drag()方法也是類似于click 隻是多了個move 事件;

sendCharacterSync(int keyCode)           //用于發送指定KeyCode的按鍵

sendKeyDownUpSync(int key)               //用于發送指定KeyCode的按鍵

sendPointerSync(MotionEvent event)    //用于模拟Touch

sendStringSync(String text)                  //用于發送字元串

繼續閱讀