1.Robotium中clickOnView的原理:
通过view.getLocationOnScreen(xyLocation)得到当前view的左上角在整个屏幕内的绝对坐标,其中xyLocation[0]-->X坐标,xyLocation[1]-->Y坐标,然后通过xyLocation[0] + (view.getWidth() / 2.0f)与xyLocation[1] + (view.getHeight() / 2.0f)得到View的中心点坐标,然后再clickOnScreen(x, y, view)。
其中clickOnScreen(x, y, view) 是通过MotionEvent.ACTION_DOWN与MotionEvent.ACTION_UP,点击坐标点来实现的。
具体代码如下:
获取坐标:
/**
* Returns click coordinates for the specified view.
*
* @param view the view to get click coordinates from
* @return click coordinates for a specified view
*/
private float[] getClickCoordinates(View view){
sleeper.sleep(MINI_WAIT);
int[] xyLocation = new int[2];
float[] xyToClick = new float[2];
view.getLocationOnScreen(xyLocation);
final int viewWidth = view.getWidth();
final int viewHeight = view.getHeight();
final float x = xyLocation[0] + (viewWidth / 2.0f);
float y = xyLocation[1] + (viewHeight / 2.0f);
xyToClick[0] = x;
xyToClick[1] = y;
return xyToClick;
}
点击:
/**
* Private method used to click on a given view.
*
* @param view the view that should be clicked
* @param longClick true if the click should be a long click
* @param time the amount of time to long click
*/
public void clickOnScreen(View view, boolean longClick, int time) {
if(view == null)
Assert.fail("View is null and can therefore not be clicked!");
float[] xyToClick = getClickCoordinates(view);
float x = xyToClick[0];
float y = xyToClick[1];
if(x == 0 || y == 0){
sleeper.sleepMini();
try {
view = viewFetcher.getIdenticalView(view);
} catch (Exception ignored){}
if(view != null){
xyToClick = getClickCoordinates(view);
x = xyToClick[0];
y = xyToClick[1];
}
}
if (longClick)
clickLongOnScreen(x, y, time, view);
else
clickOnScreen(x, y, view);
}
点击控件:
/**
* Clicks the specified View.
*
* @param view the {@link View} to click
* @param immediately {@code true} if View should be clicked without any wait
*/
public void clickOnView(View view, boolean immediately){
if(immediately)
clicker.clickOnScreen(view);
else{
view = waiter.waitForView(view, Timeout.getSmallTimeout());
clicker.clickOnScreen(view);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。