android 中按键响应实例

下面实例中是在一个Activity 中通过上下左右方向键来控制红色小方块的移动,未作边界检测

效果如下:



RectControlActivity.java

package cie.Rect;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class RectControlActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置窗口没有标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        		WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏显示        
        setContentView(new RectControlView(this));
    }
}
RectControlView.java

package cie.Rect;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.View;

public class RectControlView extends View {
	
	int left = 40;
	int top = 40;
	int width = 40;
	int height = 40;
	
	public RectControlView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		setFocusable(true);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		
		canvas.drawRect(left, top, left+width, top+height, paint);
		postInvalidate();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch(keyCode)
		{
		case KeyEvent.KEYCODE_DPAD_UP:
			top = top - 10;
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			top = top + 10;
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			left = left - 10;
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			left = left + 10;
			break;
		default:
				break;
		}
		return super.onKeyDown(keyCode, event);
	}
}




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fulinwsuafcie/article/details/7407348
个人分类: Android 基础
上一篇android Wifi 控制
下一篇make: arm-eabi-gcc: Command not found 错误解决办法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭