android中怎么实现按键监听和触屏监听?
按键监听代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch(keyCode){
case KeyEvent.KEYCODE_DPAD_UP:
y--;break;
case KeyEvent.KEYCODE_DPAD_LEFT:
x--;break;
case KeyEvent.KEYCODE_DPAD_DOWN:
y++;break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
x++;break;
}
this.invalidate();
return true;
}
触屏监听代码:
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
x=(int)event.getX();
y=(int)event.getY();
this.invalidate();
return true;
}
通过鼠标可以使图形任意移动。将apk文件下载到手机上就可以实现触屏监听。