mathexplorer
mathexplorer

Reputation: 375

Global variable reset to 0 between classes in Android

There are a few questions related to this, but I couldn't find any that helped me. My code is below. Basically touchX is set in OnTouch. Once we get to OnDraw(), it is reset to 0.

public class NonmultiplierSixView extends View implements View.OnTouchListener{
int touchX;
int touchY;
public NonmultiplierSixView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int touchX = (int)event.getX();
    int touchY = (int)event.getY();
    Log.i("STATE", Integer.toString(touchX));
    return true;
}



@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i("STATE", Integer.toString(touchX));
}


}

How do I stop it from resetting the value of touchX and touchY to 0?

Upvotes: 0

Views: 321

Answers (1)

gandalf
gandalf

Reputation: 118

You have created 2 copies of touchX and touchY.

These two,

public class NonmultiplierSixView extends View implements View.OnTouchListener {
int touchX;
int touchY;

are the instance variables (i.e. they belong to the object of class NonmultiplierSixView)

Whereas, the ones defined in the function onTouch are local copies.

public boolean onTouch(View v, MotionEvent event) {
    int touchX = (int)event.getX();
    int touchY = (int)event.getY();

In the function onDraw, you are actually accessing the instance variable touchX and not the local variable. As instance int variables have default value of 0, you are getting 0 in the onDraw function.

=============================================

Solution:

Try this

public boolean onTouch(View v, MotionEvent event) {
    this.touchX = (int)event.getX();
    this.touchY = (int)event.getY();
    Log.i("STATE", Integer.toString(this.touchX));
    return true;
}



@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i("STATE", Integer.toString(this.touchX));
}

Upvotes: 2

Related Questions