为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我按下方向键怎么却没有反应?

为什么我按下方向键怎么却没有反应?

三国纷争 2023-01-12 19:15:22

下面这个android程序我本来想按下按钮对应的方向键图片就会朝相对的方向移动。
public class MySurfaceView extends SurfaceView implements Callback, Runnable {
private SurfaceHolder sfh;
private Paint paint;
private Canvas canvas;
private Thread th;
private boolean flag;
private Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android);
private int left=100,top=100;

public MySurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setColor(Color.RED);
setFocusable(true);
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
flag = true;
th = new Thread(this);
th.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}

private void myDraw() {
// TODO Auto-generated method stub
try
{
canvas = sfh.lockCanvas();
if(canvas != null)
{
canvas.drawRGB(0, 0, 0);
canvas.drawBitmap(bmp, left, top, paint);
}
}catch (Exception e)
{}finally
{
if(canvas != null)
sfh.unlockCanvasAndPost(canvas);
}
}

public boolean onkeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_DPAD_UP)
{
top-=1;
}else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
{
top+=1;
}else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
{
left-=1;
}else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
{
left+=1;
}
return super.onKeyDown(keyCode, event);
}

public boolean onkeyUp(int keyCode, KeyEvent event)
{
return super.onKeyUp(keyCode, event);
}

public void logic(){
}

public void run() {
// TODO Auto-generated method stub
while(flag)
{
long start = System.currentTimeMillis();
myDraw();
logic();
long end = System.currentTimeMillis();
try
{
if(end - start < 20)
{
Thread.sleep(20 - (end - start));
}
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

}

查看完整描述

1 回答

?
米脂

TA贡献1597条经验 获得超3个赞

你的activity里面也有onkeydown,估计没有传进来,view的触摸传递模式是从从上面一层开始传递,要看xml里你的surfaceview的布局位置,如果view之间key值传递有onkeydown返回值设置为true,就不会再往下传了,从而surfaceview可能就没有接受到。

查看完整回答
反对 回复 2023-01-15

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信