繁体   English   中英

Android开发-OnTouchListener-如何使用?

[英]Android Development - OnTouchListener - How to Use?

我想知道一个人如何使用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;的需要是什么return false; 谢谢!

我猜您的应用程序崩溃了,因为您忘记了将权限添加到清单文件中。 确保其中包含: <uses-permission android:name="android.permission.VIBRATE" />

而且,顺便说一句,如果您想接收所有发生在View上的触摸事件,则应该在OnTouchListener return true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM