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

    转载请注明出处: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文件了。

    我们能够像以下这样调用,很easy

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