基于监听的事件处理:
飞机游戏:
1.定义一个自定义View,用来绘制飞机。
package com.mycompany.planegame; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; /** * Created by Administrator on 2017/2/21. */ public class PlaneView extends View { public float currentX; public float currentY; Bitmap plane; public PlaneView(Context context) { super(context); // 定义飞机图片 plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane); setFocusable(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 创建画笔 Paint p = new Paint(); // 绘制飞机 canvas.drawBitmap(plane, currentX, currentY, p); } }
2.利用键盘事件监听器来控制飞机移动。
package com.mycompany.planegame; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; /** * Created by Administrator on 2017/2/21. */ public class PlaneGame extends Activity { // 定义飞机移动速度 private int speed = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 去掉窗口标题 requestWindowFeature(Window.FEATURE_NO_TITLE); // 全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 创建PlaneView组件 final PlaneView planeView = new PlaneView(this); setContentView(planeView); planeView.setBackgroundResource(R.drawable.background); // 获取窗口管理器 WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); // 获得屏幕宽和高 display.getMetrics(metrics); // 设置飞机的初始位置 planeView.currentX = metrics.widthPixels / 2 - 100; planeView.currentY = metrics.heightPixels - 300; // 为draw组件键盘事件绑定监听器 planeView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // 获取用户按键 switch (event.getKeyCode()) { // 下移 case KeyEvent.KEYCODE_S: planeView.currentY += speed; break; // 上移 case KeyEvent.KEYCODE_W: planeView.currentY -= speed; break; // 左移 case KeyEvent.KEYCODE_A: planeView.currentX -= speed; break; // 右移 case KeyEvent.KEYCODE_D: planeView.currentX += speed; break; } // 通知planeView组件重绘 planeView.invalidate(); return true; } }); } }
注意:
1.屏幕坐标系以左上角为原点,以右、下为正。