我正在尝试为我的custom listview实现onTouchListner以检测滑动。
在此代码中,两个切换案例(ACTION_DOWN
,ACTION_UP
)都有效,但当ACTION_UP
触发我在downx中获得的值时,downy变为0。
并且用于检测滑动的代码总是说向右滑动(即使我只是单击!!)
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event)
{
float downx = 0,downy = 0, upx = 0, upy = 0, movex = 0, movey = 0;
switch(event.getAction())
{
case(MotionEvent.ACTION_DOWN):
{
downx = event.getX();
downy = event.getY();
Log.i("TOUCH","DOWN");
break;
}
case(MotionEvent.ACTION_UP):
{
upx = event.getX();
upy = event.getY();
Log.i("TOUCH","UP");
if(downx < upx)
{
Log.w("TODO","Swiped right");
}
else if(upx < downx)
{
Log.w("TODO","Swiped left");
}
break;
}
}
Log.i("TOUCH_DOWN","x = "+downx+"y = "+ downy);
Log.i("TOUCH_MOVE","x = "+movex+"y = "+ movey);
Log.i("TOUCH_UP","x = "+upx+"y = "+ upy);
return true;
}
});
return view;
}
}
有没有办法让它发挥作用 建议需要!! 感谢
答案 0 :(得分:1)
@Override
public boolean onTouch(View v, MotionEvent event) {
float downx = 0,downy = 0, upx = 0, upy = 0, movex = 0, movey = 0;
每次触摸事件都会调用 onTouch
,重新初始化所有本地成员。如果你想避免这种情况,请将其保留为班级成员,
答案 1 :(得分:0)
float downx = 0,downy = 0, upx = 0, upy = 0, movex = 0, movey = 0;
每次调用onTouch()时都会初始化它们 将它们全局声明为类成员。