在android中的Edittext的振动
我想创建一个编辑文本,如果给定的输入是无效的将震动。 例如编辑文本的数字,如果数字是错误的,因为它包含9位数字比编辑文本将变得清晰,并会震动一段时间如何创建? 提前致谢
在资源中创建anim文件夹,然后创建文件nmaed shake.xml并粘贴下面的代码
和另一个文件cycle_7.xml
然后在你的java文件中
if(invalid)//check your input { Animation shake = AnimationUtils.loadAnimation(Login.this, R.anim.shake); editText.startAnimation(shake); }
如果有人正在寻找一种方法来执行@ Priya以编程方式建议,那么你可以试试这个。
public TranslateAnimation shakeError() { TranslateAnimation shake = new TranslateAnimation(0, 10, 0, 0); shake.setDuration(500); shake.setInterpolator(new CycleInterpolator(7)); return shake; }
接着:
myEditText.startAnimation(shakeError());
振动使用下面的代码。
Vibrator vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
然后,在OnTextChanged侦听器方法使用下面的代码。
vibe.vibrate(50); // 50 is time in ms
不要忘记,您需要将清单(在标签之后)添加到清单中:
您应该将此侦听器添加到EditText以进行所需的validation,
editText.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // Write your logic here if(condition satisfy) // call vibrate(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); public void vibrate() { Vibrator vibrate= (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE) ; vibrate.vibrate(50); }
在anim文件夹下创建shake.xml
之后为按钮添加animation。 为了简单起见,我在Kotlin中编写了这个代码。
button.setOnClickListener { button.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake) }