用戶輸入非法內容時的震動與動畫提示——EditTextShakeHelper工具類介紹

        當用戶在EditText中輸入爲空或者是數據異常的時候,我們可以使用Toast來提醒用戶,除此之外,我們還可以使用動畫效果和震動提示,來告訴用戶:你輸入的數據不對啊!這種方式更加的友好和有趣。

    爲了完成這個需求,我封裝了一個幫助類,可以很方便的實現這個效果。

    先上代碼吧。

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



發佈了74 篇原創文章 · 獲贊 26 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章