无法使OnTouchListner正常工作

时间:2015-08-30 16:50:46

标签: java android eclipse ontouchlistener

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

活动类:

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();
    }



}

2 个答案:

答案 0 :(得分:1)

您应该只能在您创建的视图上进行设置:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GameView gv = new GameView(this);
    setContentView(gv);

    // set the touch listener for the view
    gv.setOnTouchListener(this);
}

答案 1 :(得分:1)

像这样实施: -

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;
    }

}