寫了一個打飛機的小程序,用於作爲事件監聽的學習,此程序需要有實體按鍵的手機才能執行。
PlaneView.java:
public class PlaneView extends View{
public float currentX;
public float currentY;
Bitmap plane;
public PlaneView(Context context) {
super(context);
// TODO Auto-generated constructor stub
//定義飛機圖片
plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.feiji);
setFocusable(true);
}
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint p = new Paint();
canvas.drawBitmap(plane, currentX, currentY, p);
}
}
Activity.javapublic class MainActivity extends Activity {
//定義飛機移動速度
private int speed = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final PlaneView planeView = new PlaneView(this);
setContentView(planeView);
//planeView.setBackgroundResource(R.drawable.feiji);
WindowManager win = getWindowManager();
Display dis = win.getDefaultDisplay();
int width = dis.getWidth();
int height = dis.getHeight();
//設置飛機的初始位置
planeView.currentX = width / 2;
planeView.currentY = height - 40;
//爲draw組建鍵盤事件綁定監聽器
planeView.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View source, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
//獲取由哪個鍵出發的時間
switch(event.getKeyCode())
{
case KeyEvent.KEYCODE_DPAD_DOWN:
planeView.currentY += speed;
break;
case KeyEvent.KEYCODE_DPAD_UP:
planeView.currentY -= speed;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
planeView.currentX -= speed;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
planeView.currentX += speed;
break;
}
//通知planeView組建重繪
planeView.invalidate();
return true;
}
});
}
}
個人辛勤勞動成果,如有轉載,請註明出處,謝謝。