键盘上按键,判断单击双击和长按事件
public class MainActivity extends ActionBarActivity {
private static boolean isWaitingDoubleClick = true;
private static boolean isKeyLongPress;
private static final int DOUBLE_CLICK = 350;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (event.isLongPress() == true && keyCode == KeyEvent.KEYCODE_MENU) {
event.startTracking();
System.out.println("长按");
isKeyLongPress = true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (isKeyLongPress == true) {
isKeyLongPress = false;
} else {
isKeyLongPress = false;
ClickOrDoubleClick(keyCode);
}
return super.onKeyUp(keyCode, event);
}
private void ClickOrDoubleClick(int keyCode) {
if (isWaitingDoubleClick == true && keyCode == KeyEvent.KEYCODE_MENU) {
isWaitingDoubleClick = false;
Thread thread = new Thread() {
@Override
public void run() {
try {
sleep(DOUBLE_CLICK);
if (isWaitingDoubleClick == false) {
isWaitingDoubleClick = true;
System.out.println("单击");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
} else {
isWaitingDoubleClick = true;
System.out.println("双击");
}
}
}