0

只要用户单击按钮,我希望设备振动。如果用户长时间按下按钮,只要用户点击并按住,设备就会振动。这是我实施的,但它适用于特定时间段。

final Button button = (Button) findViewById(R.id.button1);

button.setOnLongClickListener(new OnLongClickListener() {   

    @Override
    public boolean onLongClick(View v) {
        if(v==button){
            Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(1000);
       }                
       return false;
    }
});
4

2 回答 2

1

实现 ontouch 侦听器并在事件关闭时执行此操作

@Override
public boolean onTouch(View v, MotionEvent event) {

    //int action = event.getAction();
    switch (event.getAction()){
    case MotionEvent.ACTION_DOWN:
       // put your code here


    break;
于 2013-06-16T21:39:07.833 回答
1

要无限地振动,您可以使用振动模式:

// 0 - start immediatelly (ms to wait before vibration)
// 1000 - vibrate for 1s
// 0 - not vibrating for 0ms
long[] pattern = {0, 1000, 0};
vb.vibrate(pattern, 0);

可以使用以下方法取消振动:

vb.cancel();

onTouch事件开始振动- ACTION_DOWN, 停止振动ACTION_UP

编辑:最终工作代码:

    final Button button = (Button) findViewById(R.id.button1);
    button.setOnTouchListener(new OnTouchListener() {
        Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    long[] pattern = {0, 1000, 0};
                    vb.vibrate(pattern, 0);
                    break;
                case MotionEvent.ACTION_UP:
                    vb.cancel();
                    break;
            }
            return false;
        }
    });
于 2013-06-16T21:41:02.623 回答