我想知道如何使用OnTouchListener
。 (我正在使用Android Studio。)
这是我的代码,当我按下“振动”按钮时,按钮图像不会改变为按下状态:
vibrateButton = (Button) findViewById(R.id.button_vibrate);
vibrationInstance = (Vibrator) getSystemService(this.VIBRATOR_SERVICE);
vibrateButtonPressed = false;
if (!(vibrationInstance.hasVibrator())) {
vibrateButton.setEnabled(false);
}
vibrateButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
vibrationInstance.cancel();
}
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
vibrationInstance.vibrate(vibrationPattern, 0);
}
return false;
}
});
使用OnTouchListener
是如何使用return false;
需要什么?谢谢!
答案 0 :(得分:1)
我猜您的应用程序崩溃了,因为您忘记将权限添加到清单文件中。确保它在其中:<uses-permission android:name="android.permission.VIBRATE" />
顺便说一句,如果您想接收视图中发生的所有触摸事件,您应return true
中的OnTouchListener
。