你如何从InstrumentationTestCase发送长按?

时间:2010-05-26 16:02:53

标签: android unit-testing keyevent

在Android中,如何从InstrumentationTestCase发送长按?例如,我想做一个sendKeys(KEYCODE_DPAD_CENTER),但要长按一下。

3 个答案:

答案 0 :(得分:2)

不知道这是否是唯一/正确的方式,但我设法这样做:

public void longClickDpadCenter() throws Exception {
    getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER));
    Thread.sleep(ViewConfiguration.get(mContext).getLongPressTimeout());
    getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
}

答案 1 :(得分:0)

您可以尝试以下辅助方法:

private void longPress(int key) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    KeyEvent event1 = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, key, 0);
    KeyEvent event2 = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, key, 1);
    getInstrumentation().sendKeySync(event1);
    getInstrumentation().sendKeySync(event2);
}

使用示例:

longPress(KeyEvent.KEYCODE_ENTER);

答案 2 :(得分:0)

android source code中的第179行:

Ex : TextController firstname;

firstname.text='' or null;