Search code examples
javaandroidontouchlistener

Cannot resolve symbol setOnTouchListener


I want to set a touch event that only occurs when player object is touched. But why my player class still cannot use setOnTouchListener method? I put it in a main class that extends SurfaceView and implements SurfaceHolder.Callback, it says cannot resolve symbol on

player.setOnTouchListener(new View.OnTouchListener){
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    }; 

My player class extends GameObject(Which is just an abstract class containing object properties) and implements View.OnTouchListener. I have also override the method in the player class itself.

@Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }

Any idea? Thanks.

EDIT:

@Override
public void surfaceCreated(SurfaceHolder holder){
    bg = new Background(BitmapFactory.decodeResource(getResources(),R.drawable.background));
    player = new Player(BitmapFactory.decodeResource(getResources(),R.drawable.character),WIDTH/2,HEIGHT/2+40,80,75,14);
    safeArea = new SafeArea(WIDTH/2,HEIGHT/2,100,40);
    bouncer = new ArrayList<Bouncer>();

    thread = new MainThread(getHolder(), this);

    //Start the game loop
    thread.setRunning(true);
    thread.start();
    setOnTouchListener(player);
}

Solution

  • As you said the player's class implements View.OnTouchListener. Obviously class View.OnTouchListener does not has method setOnTouchListener().

    You should review your intention. Do you want player to implement View instead? Or whose OnTouchListener do you want to set actually?

    Since your "main class" extends SurfaceView, it looks like you may want

    setOnTouchListener(player);
    

    which sets player as the OnTouchListener of the "main class" instance, which is also a SurfaceView and thus is a View.

    To define player.onTouch(), you should define it inside class Player like:

    class Player implements View.OnTouchListener // extends GameObject ?
    {
        // ...
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    }