gpt4 book ai didi

java - 无法让 OnTouchListner 工作

转载 作者:行者123 更新时间:2023-11-29 20:28:11 26 4
gpt4 key购买 nike

我正在尝试创建我的第一个 android 游戏(在 eclipse 中),但我似乎无法让 OnTouchListner 工作,主要是因为我不知道如何或在哪里创建它。我想弄清楚有人点击屏幕的位置。谁能告诉我如何以及在何处创建 OnTouchListner!

Activity 类:

package com.gregsapps.fallingbird;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class Game extends Activity implements OnTouchListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.){
System.out.println("TOUCH");
}
return false;
}

}

查看类:

package com.gregsapps.fallingbird;

import android.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View{

private Bird bird;
private boolean runOnce = false;
private Context context;

public GameView(Context context) {
super(context);
this.context = context;
this.setDrawingCacheEnabled(true);
// TODO add setup code
}

protected void onDraw(Canvas canvas){
update(canvas);
//TODO add drawing code
this.buildDrawingCache();
//bird.canvasImage = this.getDrawingCache(true);
canvas.drawBitmap(bird.image, bird.x, bird.y, null);
System.out.println("drawing");
invalidate();
}

private void update(Canvas canvas){
//TODO add code to update stuff
if(runOnce == false){
bird = new Bird(canvas, com.gregsapps.fallingbird.R.drawable.bird, context);
runOnce = true;
}
bird.move();
}



}

最佳答案

像这样实现它:-

public class Game extends Activity implements OnTouchListener{
GameView gv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gv = new GameView(this);
setContentView(gv);

gv.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = event.getX();
int y = event.getY();
System.out.println("Touched view at X: " + X + " Y: " + Y );
}
return false;
}

}

关于java - 无法让 OnTouchListner 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com