我正在尝试监听触摸释放,但事件没有被触发。
这是我的代码:
public class MyView extends View {
public MyView(final Context context) {
super(context);
setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
makeToast("press", context);
} else if (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL) {
makeToast("release", context);
}
return false;
}
});
}
void makeToast(String s, Context c) {
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(c, text, duration);
toast.show();
}
}
Activity 类别:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView v = new MyView(getApplicationContext());
setContentView(v);
}
}
发生的情况是,当我触摸屏幕时,会出现一个写有“press”的 toast ,但是当我释放触摸时,不会出现 toast ,而我期待一个写有“release”的 toast 出现。
我错过了什么?
最佳答案
您需要在 onTouchListener 中返回 true 而不是 false。
发生的情况是,首先触发了“向下操作”,但您返回了 false,这意味着未处理“向下操作”。
如果您返回 true,它将确保它捕获的每个操作都得到充分处理,只有当您知道需要其他 View 来处理该操作时,您才会返回 false。
祝你好运!
关于java - Android 监听触摸释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19820764/