So you this nice android application but you need to test the UI using some touch screen touch events in which you the developer supply the x and y coords in you test class. Right now there is not a TouchUtils method for this set of use cases. The method I came up with probably looks like this:
/**
*
* @param test
* @param view
* @param touchX in DIPs
* @param touchY in DIPs
*/
static void touchPoint(InstrumentationTestCase test, View view, float touchX, float touchY, Activity activity ) {
Instrumentation inst = test.getInstrumentation();
float screenDensity;
float screenWidthPx;
float screenHeightPx;
float touchTempX;
float touchTempY;
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis();
/**
* 1 dip = 1 pixel thus
* dip x density = pixels
*
* density of 1 equals
* 160 dpi 240x320 baseline display or 1.5"x2"
*/
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
screenDensity = dm.density;
screenHeightPx = dm.heightPixels;
screenWidthPx = dm.widthPixels;
if (touchX * screenDensity <= screenWidthPx){
touchTempX = touchX * screenDensity;
}else{
touchTempX = 1;
}
if (touchY * screenDensity <= screenHeightPx) {
touchTempY = touchY *screenDensity;
}else{
touchTempY = 1;
}
// touch down
MotionEvent event = MotionEvent.obtain(downTime, eventTime,
MotionEvent.ACTION_DOWN, touchTempX, touchTempY, 0);
inst.sendPointerSync(event);
inst.waitForIdleSync();
// touch up
MotionEvent eventUp = MotionEvent.obtain(downTime, eventTime,
MotionEvent.ACTION_UP, touchTempX, touchTempY, 0);
inst.sendPointerSync(eventUp);
inst.waitForIdleSync();
}
It should work. notice that it defaults to coords of 1,1 if you the developer goof up on your x and y cordinate inputs as its expected that you input your x and Y coordinates in terms of DIP not pixels so that your unit tests will always work no mater what the screen size.



![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=146bec7a-9fab-42a3-b4cc-cc0e992484b3)