[英]Vibrate until the button is pressed and stops vibrating when the button is unpressed (or the finger is taken off)
我打算對按鈕進行編程,以便在按下按鈕時開始振動並一直振動,直到手指抬起或未按下按鈕為止。
我為此目的在Touch Listener上使用。
我的代碼如下:
package com.example.vibrator;
import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Vibrator vibrator;
vibrator = (Vibrator) getSystemService(MainActivity.VIBRATOR_SERVICE);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
vibrator.vibrate(60000);
} else if (action == MotionEvent.ACTION_UP) {
vibrator.cancel();
}
return true;
}
});
}
}
該代碼中的問題在於,它會不斷振動,並且當手指向上時,振動不會停止或消除。
PS我已使用清單中的許可
編輯 :更正的代碼:
嘗試這個:
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
long[] pattern = { 0, 200, 0 }; //0 to start now, 200 to vibrate 200 ms, 0 to sleep for 0 ms.
vibrator.vibrate(pattern, 0); // 0 to repeat endlessly.
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
vibrator.cancel();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.