用户输入非法内容时的震动与动画提示

来源:互联网 发布:幼儿教育软件哪个好 编辑:程序博客网 时间:2024/04/29 00:11


http://blog.csdn.net/zhaokaiqiang1992/article/details/41344937


用户输入非法内容时的震动与动画提示——EditTextShakeHelper工具类介绍

标签: animationedittext震动
 2860人阅读 评论(1) 收藏 举报
 分类:
 

    转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992

    当用户在EditText中输入为空或者是数据异常的时候,我们可以使用Toast来提醒用户,除此之外,我们还可以使用动画效果和震动提示,来告诉用户:你输入的数据不对啊!这种方式更加的友好和有趣。

    为了完成这个需求,我封装了一个帮助类,可以很方便的实现这个效果。

    先上代码吧。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.   
  2. package com.example.sharkdemo;  
  3.   
  4. import android.app.Service;  
  5. import android.content.Context;  
  6. import android.os.Vibrator;  
  7. import android.view.animation.Animation;  
  8. import android.view.animation.CycleInterpolator;  
  9. import android.view.animation.TranslateAnimation;  
  10. import android.widget.EditText;  
  11.   
  12. /** 
  13.  *  
  14.  * @ClassName: com.example.sharkdemo.EditTextShakeHelper 
  15.  * @Description:输入框震动效果帮助类 
  16.  * @author zhaokaiqiang 
  17.  * @date 2014-11-21 上午9:56:15 
  18.  *  
  19.  */  
  20. public class EditTextShakeHelper {  
  21.   
  22.     // 震动动画  
  23.     private Animation shakeAnimation;  
  24.     // 插值器  
  25.     private CycleInterpolator cycleInterpolator;  
  26.     // 振动器  
  27.     private Vibrator shakeVibrator;  
  28.   
  29.     public EditTextShakeHelper(Context context) {  
  30.   
  31.         // 初始化振动器  
  32.         shakeVibrator = (Vibrator) context  
  33.                 .getSystemService(Service.VIBRATOR_SERVICE);  
  34.         // 初始化震动动画  
  35.         shakeAnimation = new TranslateAnimation(01000);  
  36.         shakeAnimation.setDuration(300);  
  37.         cycleInterpolator = new CycleInterpolator(8);  
  38.         shakeAnimation.setInterpolator(cycleInterpolator);  
  39.   
  40.     }  
  41.   
  42.     /** 
  43.      * 开始震动 
  44.      *  
  45.      * @param editTexts 
  46.      */  
  47.     public void shake(EditText... editTexts) {  
  48.         for (EditText editText : editTexts) {  
  49.             editText.startAnimation(shakeAnimation);  
  50.         }  
  51.   
  52.         shakeVibrator.vibrate(new long[] { 0500 }, -1);  
  53.   
  54.     }  
  55.   
  56. }  

    代码非常的少哈,而且为了使用起来更加方便,我直接把动画的设置写在代码里面了,这样就不需要额外的xml文件了。

    我们可以像下面这样调用,非常简单

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (TextUtils.isEmpty(et.getText().toString())) {  
  2. new EditTextShakeHelper(MainActivity.this).shake(et);  
  3. }  

    使用之前不要忘记加上震动的权限

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

    这个项目的github地址:https://github.com/ZhaoKaiQiang/EditTextShakeHelper



0 0