爲了完成這個需求,我封裝了一個幫助類,可以很方便的實現這個效果。
先上代碼吧。
/*
* File Name:EditTextShakeHelper.java
*/
import android.app.Service;
import android.content.Context;
import android.os.Vibrator;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
public class EditTextShakeHelper {
// 震動動畫
private Animation shakeAnimation;
// 插值器
private CycleInterpolator cycleInterpolator;
// 振動器
private Vibrator shakeVibrator;
public EditTextShakeHelper(Context context) {
// 初始化振動器
shakeVibrator = (Vibrator) context
.getSystemService(Service.VIBRATOR_SERVICE);
// 初始化震動動畫
shakeAnimation = new TranslateAnimation(0, 10, 0, 0);
shakeAnimation.setDuration(300);
cycleInterpolator = new CycleInterpolator(8);
shakeAnimation.setInterpolator(cycleInterpolator);
}
/**
* 開始震動
*
* @param editTexts
*/
public void shake(EditText... editTexts) {
for (EditText editText : editTexts) {
editText.startAnimation(shakeAnimation);
}
shakeVibrator.vibrate(new long[] { 0, 500 }, -1);
}
}
我們可以像下面這樣調用,非常簡單
if (TextUtils.isEmpty(et.getText().toString())) {
new EditTextShakeHelper(MainActivity.this).shake(et);
}