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);
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。