Android键盘事件监听器实例-能移动的飞机

Android键盘事件监听器实例-能移动的飞机_第1张图片

通过键盘控制飞机的上下左右移动,如果出现 DPAD not enabled in AVD ,参考本人之前的那篇文章

首先,建立一个PlaneView.java

package com.example.moveplaneevent;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

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);
}
}

Main.java

package com.example.moveplaneevent;

import android.os.Bundle;
import android.app.Activity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class PlaneGame 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);
setContentView(R.layout.activity_main);
//创建一个PlaneView对象
final PlaneView planeView=new PlaneView(PlaneGame.this);

setContentView(planeView);

//获取窗口管理器
WindowManager windowManager=getWindowManager();
Display display=windowManager.getDefaultDisplay();
//获取屏幕的宽和高
int screenWidth=display.getWidth();
int screenHeight=display.getHeight();

//设置飞机的初始位置,设置水平居中
planeView.currentX=screenWidth/2-(planeView.plane.getWidth()/2);
planeView.currentY=screenHeight-250;

//为draw组件设置键盘监听器
planeView.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View source, int keyCode, KeyEvent event) {

//获取由那个键触发的事件
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.invalidate();
return true;
}
});
    }

public void displayToast(String text){
Toast toast=Toast.makeText(PlaneGame.this,text,Toast.LENGTH_LONG);
toast.show();
}
}

你可能感兴趣的:(Android键盘事件监听器实例-能移动的飞机)