Android: How to create a MotionEvent?

前端 未结 2 1197
粉色の甜心
粉色の甜心 2020-11-29 01:30

MotionEvent doesn\'t get a constructor, I wanted to manually create a MotionEvent in my unit test, then how to get that? Thanks.

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 01:50

    Supplemental answer

    Here is an example illustrating the accepted answer:

    // get the coordinates of the view
    int[] coordinates = new int[2];
    myView.getLocationOnScreen(coordinates);
    
    // MotionEvent parameters
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    int action = MotionEvent.ACTION_DOWN;
    int x = coordinates[0];
    int y = coordinates[1];
    int metaState = 0;
    
    // dispatch the event
    MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, metaState);
    myView.dispatchTouchEvent(event);
    

    Notes

    • Other meta states include things like KeyEvent.META_SHIFT_ON, etc.
    • Thanks to this answer for help with the example.

提交回复
热议问题