有一些与此相关的问题,但我找不到任何对我有帮助的问题。我的代码如下。基本上touchX是在OnTouch中设置的。一旦我们到达 OnDraw(),它就会重置为 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));
}
}
如何阻止它将 touchX 和 touchY 的值重置为 0?
最佳答案
您已创建 touchX
和 touchY
的 2 个副本。
这两个,
public class NonmultiplierSixView extends View implements View.OnTouchListener {
int touchX;
int touchY;
是实例变量(即它们属于NonmultiplierSixView
类的对象)
而函数onTouch
中定义的是本地副本。
public boolean onTouch(View v, MotionEvent event) {
int touchX = (int)event.getX();
int touchY = (int)event.getY();
在函数onDraw
中,您实际上访问的是实例变量touchX
,而不是局部变量。由于实例 int
变量的默认值为 0
,因此您将在 onDraw
函数中获取 0
。
================================================
解决方案:
试试这个
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));
}
关于java - Android 中类之间的全局变量重置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712478/