码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-11-21 10:39:28      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:des   android   blog   http   io   ar   os   使用   sp   

    转载请注明出处: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" />

    

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

标签:des   android   blog   http   io   ar   os   使用   sp   

原文地址:http://blog.csdn.net/zhaokaiqiang1992/article/details/41344937

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!