在我的应用程序中,我想计算两个距离之间的比率,但我不知道为什么变量dist1和dist2没有保存我在IF ELSE语句中计算的值,我的编码有什么问题?
任何指导或帮助将不胜感激。
这是编码方法:
@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;
}
答案 0 :(得分:2)
您正尝试从两个单独的触摸事件中设置dist1
和dist2
。您已在onTouchEvent()
方法中声明了这两个变量。一旦此方法返回,变量就会超出范围并停止存在。
您需要做的是将它们声明为会在多个触摸事件中持续存在的地方。最简单的方法是将它们声明为周围类的成员。
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
...
}