两个Java。第一个负责绘制飞机,主Activity负责控制飞机的初始坐标和飞行,不需要layout布局
------------------绘制飞机---------------------------
PlaneView.java
package com.example.admin.webchanjian; 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 admin on 2016/10/6. */ public class PlainView extends View { public float currentX; public float currentY; Bitmap plane; public PlainView(Context context){ super(context); plane= BitmapFactory.decodeResource(context.getResources(),R.drawable.plane); setFocusable(true); } @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); Paint p=new Paint(); canvas.drawBitmap(plane,currentX,currentY,p); } } -----------------------------控制飞机飞行-------------------- MainActivity.java
//-------------------Playing Plane------------------------------ private int speed=10; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去掉窗口标题 requestWindowFeature(Window.FEATURE_NO_TITLE); //全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //创建PlaneView组件 final PlainView plainView=new PlainView(this); setContentView(plainView); plainView.setBackgroundResource(R.drawable.back); //获取窗口管理器 WindowManager windowManager=getWindowManager(); Display display=windowManager.getDefaultDisplay(); DisplayMetrics displayMetrics=new DisplayMetrics(); //获取屏幕宽和高 display.getMetrics(displayMetrics); //设置plane的初始位置 plainView.currentX=displayMetrics.widthPixels/2; plainView.currentY=displayMetrics.heightPixels-40; //为PlaneView组件的键盘事件绑定监听器 plainView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (event.getKeyCode()){ //下移 case KeyEvent.KEYCODE_S: plainView.currentY+=speed; break; //上移 case KeyEvent.KEYCODE_W: plainView.currentY-=speed; break; //左移 case KeyEvent.KEYCODE_A: plainView.currentX-=speed; break; case KeyEvent.KEYCODE_D: plainView.currentX+=speed; break; } //通知PlaneView组件重绘 plainView.invalidate(); return true; } }); }