Android的事件处理-android学习之旅(四十四)
androd事件处理简单介绍
控制飞机移动的简单实例
package peng.liu.test;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity{
int speed = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Plane plane = new Plane(this);
setContentView(plane);
plane.setBackgroundResource(Color.RED);
WindowManager manager = getWindowManager();
Display display = manager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
plane.currentX = metrics.widthPixels/2;
plane.currentY = metrics.heightPixels-40;
plane.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
switch(keyEvent.getKeyCode()){
case KeyEvent.KEYCODE_S:
plane.currentY+=speed;
break;
case KeyEvent.KEYCODE_W:
plane.currentY-=speed;
break;
case KeyEvent.KEYCODE_A:
plane.currentX-=speed;
break;
case KeyEvent.KEYCODE_D:
plane.currentX+=speed;
break;
}
plane.invalidate();
return true;
}
});
}
}
package peng.liu.test;
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 lplp on 2015/6/10.
*/
public class Plane extends View {
public float currentX,currentY;
public Bitmap plane;
public Plane(Context context){
super(context);
plane = BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint();
canvas.drawBitmap(plane,currentX,currentY,p);
}
}