ShadowMotionEvent.java revision 93d2e533a569470d2901b9d20d9113e3f9761563
1package com.xtremelabs.robolectric.shadows;
2
3import android.view.MotionEvent;
4import com.xtremelabs.robolectric.Robolectric;
5import com.xtremelabs.robolectric.internal.Implementation;
6import com.xtremelabs.robolectric.internal.Implements;
7import com.xtremelabs.robolectric.internal.RealObject;
8
9import java.lang.reflect.Constructor;
10
11/**
12 * Shadow for {@code MotionEvent} that uses reflection to create {@code MotionEvent} objects, which cannot otherwise
13 * be constructed.
14 */
15@SuppressWarnings({"UnusedDeclaration"})
16@Implements(MotionEvent.class)
17public class ShadowMotionEvent {
18    @RealObject private MotionEvent realObject;
19
20    private int action;
21    private float[] x = new float[2];
22    private float[] y = new float[2];
23    private int pointerCount = 1;
24
25    @Implementation
26    public static MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, int metaState) {
27        try {
28            Constructor<MotionEvent> constructor = MotionEvent.class.getDeclaredConstructor();
29            constructor.setAccessible(true);
30            MotionEvent motionEvent = constructor.newInstance();
31            ShadowMotionEvent shadowMotionEvent = (ShadowMotionEvent) Robolectric.shadowOf_(motionEvent);
32            shadowMotionEvent.x[0] = x;
33            shadowMotionEvent.y[0] = y;
34            shadowMotionEvent.action = action;
35            return motionEvent;
36        } catch (Exception e) {
37            throw new RuntimeException(e);
38        }
39    }
40
41    @Implementation
42    public int getAction() {
43        return action;
44    }
45
46    @Implementation
47    public final float getX() {
48        return getX(0);
49    }
50
51    @Implementation
52    public final float getY() {
53        return getY(0);
54    }
55
56    @Implementation
57    public final float getX(int pointerIndex) {
58        return x[pointerIndex];
59    }
60
61    @Implementation
62    public final float getY(int pointerIndex) {
63        return y[pointerIndex];
64    }
65
66    @Implementation
67    public final int getPointerCount() {
68    	return pointerCount;
69    }
70
71    public MotionEvent setPointer2(float x, float y) {
72        this.x[1] = x;
73        this.y[1] = y;
74        pointerCount = 2;
75        return realObject;
76    }
77}
78