用户输入非法内容时的震动与动画提示——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文件了。

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值