jeudi 16 juin 2016

Why my view does not get my touch event

I have the following code:

package com.teste;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;


public class ball extends View implements View.OnTouchListener {

    Bitmap littleBall;
    float x, y;
    private int mWidth, mHeight;
    private GestureDetector mDetector;

    public ball(Context context) {
        super(context);
    }

    public ball(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        mDetector = new GestureDetector(this.getContext(), new BallListener());

    }

    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        mHeight = View.MeasureSpec.getSize(heightMeasureSpec);

        x = mWidth/2;
        y = mHeight/2;

        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        littleBall = BitmapFactory.decodeResource(getResources(), R.drawable.verde);
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(littleBall, 200, 200, false);
        canvas.drawBitmap(resizedBitmap, (x - (resizedBitmap.getWidth() / 2)), (y - resizedBitmap.getHeight()/2), null);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Toast.makeText(getContext(), "teste", Toast.LENGTH_LONG);
        return mDetector.onTouchEvent(event);
    }

    class BallListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            if (e.getAction() == MotionEvent.ACTION_UP) {
                x = e.getX();
                y = e.getY();
                invalidate();
            }
            return super.onSingleTapUp(e);
        }
    }
}

In a near future i want make the ball moves to a place when i swipe my finger across the screen. But for the start, my goal is make the LittleBall (created using canvas and bitmap) change its position when i touch at the screen. I am using onTouch and a gestureListener. Searching on the net, i found others ways to get a touch like onTouchListener and even looking and Android Developer Help i did not understand what is the difference between those methods...

Can Someone explain in a easy way when i should use those methods and what im doing wrong?

Aucun commentaire:

Enregistrer un commentaire