我想在用户将手放在视图上并放开时停止它的同时做一些工作。我的代码如下:
viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
private Handler mHandler;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(mHandler==null)
mHandler = new Handler();
mHandler.postDelayed(mAction, 500);
return true;
case MotionEvent.ACTION_UP:
Log.v("this","cancel");
if (mHandler != null) {
mHandler.removeCallbacks(mAction);
mHandler = null;
Log.v("this", "c cancel");
}
break;
}
return false;
}
Runnable mAction = new Runnable() {
@Override public void run() {
ChangeTedad(item.getid(), "plus");
Log.v("this","Cc");
mHandler.postDelayed(this, 500);
}
};
});
问题是,从不调用ACTION_UP,并且可运行的指针将永远运行。
用户取消触摸时如何停止可运行文件?
最佳答案
您没有在触摸事件中正确设置中断和返回标志。
请替换为您的代码,
viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
private Handler mHandler;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(mHandler==null)
mHandler = new Handler();
mHandler.postDelayed(mAction, 500);
break;
case MotionEvent.ACTION_UP:
Log.v("this","cancel");
if (mHandler != null) {
mHandler.removeCallbacks(mAction);
mHandler = null;
Log.v("this", "c cancel");
}
break;
}
return true;
}
Runnable mAction = new Runnable() {
@Override public void run() {
ChangeTedad(item.getid(), "plus");
Log.v("this","Cc");
mHandler.postDelayed(this, 500);
}
};
});
希望对你有帮助