Search code examples
androidontouch

Android OnTouch method value unable to initialized


In my application I want to calculate the ratio between two distance, but I don't know why the variable dist1 and dist2 are not save the value that I have calculated in the IF ELSE statement, what is wrong in my coding?

Any guidance or help will be appreciated.

This is the method coding:

@Override
public boolean onTouchEvent(MotionEvent event) {
    final int action = event.getAction() & MotionEvent.ACTION_MASK;
    float x, y, x1, x2, y1, y2, dist1, dist2;
    int pointerIndex;

    if(event.getPointerCount()==1){
        if (action == MotionEvent.ACTION_DOWN) {
            x = event.getX();
            y = event.getY();
        } else {
            pointerIndex = event.getActionIndex();
            x = event.getX(pointerIndex);
            y = event.getY(pointerIndex);
        }
        mRenderer.setXY(x, y);
        requestRender();
    }
    if(event.getPointerCount()==2){
        if (action == MotionEvent.ACTION_POINTER_UP) {
            x1 = event.getX(0);
            y1 = event.getY(0);
        }else {
            x1 = event.getX(0);
            y1 = event.getY(0);
        }
        if (action == MotionEvent.ACTION_POINTER_DOWN) {
            x2 = event.getX(1);
            y2 = event.getY(1);
            dist1 = (float)Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
            Log.v("DIST1: ", String.valueOf(dist1));
        } else {
            x2 = event.getX(1);
            y2 = event.getY(1);
            dist2 = (float)Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
            Log.v("DIST2: ", String.valueOf(dist2));
        }
        ratio = dist2/dist1;//here the dist2 and dist1 is not initialized
    }
    return true;
}

Solution

  • You are trying to set dist1 and dist2 from two separate touch events. You have declared these two variables within the onTouchEvent() method. As soon as this method returns the variables go out of scope and cease to exist.

    What you need to do is declare them somewhere that will persist over multiple touch events. The easiest way to do this is to declare them as members of the surrounding class.

    private float dist1, dist2;
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x, y, x1, x2, y1, y2; // Do not re-declare dist1 and dist2 here
        ...
    }