문제

I want the device to vibrate as long as the user clicks the button. If the user press the button for a long period of time the device is to vibrate as long as the user clicks and holds. here is what I implemented but it works for a particular period of time.

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;
    }
});
도움이 되었습니까?

해결책

To vibrate indefinitelly you can use vibration pattern:

// 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);

Vibration can be cancelled using:

vb.cancel();

Start vibration on onTouch event - ACTION_DOWN, stop vibration on ACTION_UP

EDIT: final working code:

    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;
        }
    });

다른 팁

implement ontouch listener and perform this action in event down

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

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


    break;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top