ShadowMotionEvent.java revision a0c53bf0d2241a08df8dc302ca275407c806dde8
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 long downTime;
24    private long eventTime;
25
26    @Implementation
27    public static MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, int metaState) {
28        try {
29            Constructor<MotionEvent> constructor = MotionEvent.class.getDeclaredConstructor();
30            constructor.setAccessible(true);
31            MotionEvent motionEvent = constructor.newInstance();
32            ShadowMotionEvent shadowMotionEvent = (ShadowMotionEvent) Robolectric.shadowOf_(motionEvent);
33            shadowMotionEvent.x[0] = x;
34            shadowMotionEvent.y[0] = y;
35            shadowMotionEvent.action = action;
36            shadowMotionEvent.downTime = downTime;
37            shadowMotionEvent.eventTime = eventTime;
38            return motionEvent;
39        } catch (Exception e) {
40            throw new RuntimeException(e);
41        }
42    }
43
44    @Implementation
45    public static MotionEvent obtain(MotionEvent motionEvent) {
46        return obtain(motionEvent.getDownTime(), motionEvent.getEventTime(), motionEvent.getAction(), motionEvent.getX(), motionEvent.getY(), motionEvent.getMetaState());
47    }
48
49    @Implementation
50    public int getAction() {
51        return action;
52    }
53
54    @Implementation
55    public final float getX() {
56        return getX(0);
57    }
58
59    @Implementation
60    public final float getY() {
61        return getY(0);
62    }
63
64    @Implementation
65    public final float getX(int pointerIndex) {
66        return x[pointerIndex];
67    }
68
69    @Implementation
70    public final float getY(int pointerIndex) {
71        return y[pointerIndex];
72    }
73
74    @Implementation
75    public final long getEventTime() {
76        return eventTime;
77    }
78
79    @Implementation
80    public final long getDownTime() {
81        return downTime;
82    }
83
84    public MotionEvent setPointer2(float x, float y) {
85        this.x[1] = x;
86        this.y[1] = y;
87        return realObject;
88    }
89}
90