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

ph44 9年前發布 | 2K 次閱讀 Java Android

轉載請注明出處: http://blog.csdn.net/zhaokaiqiang1992

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

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

    先上代碼吧。

    /* 
     * Copyright (c) 2014, 青島司通科技有限公司 All rights reserved. 
     * File Name:EditTextShakeHelper.java 
     * Version:V1.0 
     * Author:zhaokaiqiang 
     * Date:2014-11-21 
     */  

    package com.example.sharkdemo;  

    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;  

    /** 
     *  
     * @ClassName: com.example.sharkdemo.EditTextShakeHelper 
     * @Description:輸入框震動效果幫助類 
     * @author zhaokaiqiang 
     * @date 2014-11-21 上午9:56:15 
     *  
     */  
    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);  

        }  

    }  


    代碼非常的少哈,而且為了使用起來更加方便,我直接把動畫的設置寫在代碼里面了,這樣就不需要額外的xml文件了。

    我們可以像下面這樣調用,非常簡單

    if (TextUtils.isEmpty(et.getText().toString())) {  
    new EditTextShakeHelper(MainActivity.this).shake(et);  
    }  

使用之前不要忘記加上震動的權限

    <uses-permission android:name="android.permission.VIBRATE" />

    這個項目的github地址:https://github.com/ZhaoKaiQiang/EditTextShakeHelper

 本文由用戶 ph44 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!