2013-03-14 42 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) 
}