2013-03-14 66 views
16

我想创建一个编辑文本,如果给定的输入无效将会振动。 例如编辑文本的数字,如果数字是错误的,像它包含9位数字比编辑文本将变得清晰,并会振动一段时间 如何创建? 在此先感谢振动Edittext在Android中

+0

Vibrator vibe =(振动器)context.getSystemService(Context.VIBRATOR_SERVICE);我用这个BT它不工作 – 2013-03-14 05:37:47

回答

30

创建资源动画文件夹,然后创建文件nmaed shake.xml 和粘贴下面的代码

<?xml version="1.0" encoding="utf-8"?> 
<translate xmlns:android="http://schemas.android.com/apk/res/android" 
    android:fromXDelta="0" android:toXDelta="10" android:duration="1000" 
    android:interpolator="@anim/cycle_7" /> 

和其他文件cycle_7.xml

<?xml version="1.0" encoding="utf-8"?> 
<cycleInterpolator xmlns:android="schemas.android.com/apk/res/android" android:cycles="7" /> 

,然后在你的java文件

if(invalid)//check your input 
{ 
    Animation shake = AnimationUtils.loadAnimation(Login.this, R.anim.shake); 
    editText.startAnimation(shake); 
} 
+0

什么是cycle_7? – 2013-03-14 05:35:32

+0

在您的anim文件夹中创建cycle_7.xml并粘贴此代码 Priya 2013-03-14 05:37:53

+0

它工作吗现在? – Priya 2013-03-14 05:43:48

4

振动请使用以下代码。

Vibrator vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); 

然后,在OnTextChanged Listener方法中使用下面的代码。

vibe.vibrate(50); // 50 is time in ms 

而且不要忘记,你需要允许添加到清单(在</application>标签后):

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

你应该这个监听器添加到EditText上您想要的验证,

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); 
     } 
8

如果有人正在寻找做@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()); 
+2

与XML相比,这感觉更清晰。 – kanudo 2017-08-19 08:16:51

0

创建shake.xml动画文件夹

<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <translate 
     android:fromXDelta="-10" 
     android:toXDelta="10" 
     android:repeatCount="5" 
     android:repeatMode="reverse" 
     android:interpolator="@android:anim/linear_interpolator" 
     android:duration="70" /> 
</set> 

下,在此之后添加动画按钮。为了简单起见,我在Kotlin中编写了这些代码。

button.setOnClickListener { 
     button.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake) 
}