2013-03-05 71 views
-1

在我的EditText中,我想輸入第一個字符作爲alpha,剩下的就是什麼。我在TextWatcher的幫助下完成了這項任務。但現在我的問題是,如果我輸入了錯誤的東西(比如數字,特殊字符)作爲我的第一個字符,那麼我的EditText不應該接受剩餘的字符。如果我糾正了我的第一個字符,那麼只有我的EditText應該接受。他們有可能實現這個朋友嗎?如果是的話請引導我的朋友。使EditText只接受alpha作爲第一個字符

我textWatcher代碼是提前

edittext.addTextChangedListener(new TextWatcher() { 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 

    } 

    public void beforeTextChanged(CharSequence s, int start, int count, 
      int after) { 

    } 

    public void afterTextChanged(Editable s) {   
     if (s.length() > 0) { 
      String str = edittext.getText().toString(); 
      char t = str.charAt(0); 
      if (!Character.isLetter(t)) { 
       Toast.makeText(getApplicationContext(), 
         "please enter your first charecter as alpha", 
         Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 
}); 

感謝。

+0

不,但\ /那個人確實;-) – 2013-03-05 07:26:28

+0

如果你不包括你在問題中嘗試過的內容,你通常會得到贊成票。如果沒有包含它,任何人都無法告訴你,在請求某人爲你解決問題之前,你確實已經努力工作。因此,養成在未來的所有問題中包括你所嘗試過的東西(代碼特別有用)的習慣。 – yarian 2013-03-05 07:32:25

+1

從查看Amit的答案,我還會建議您在發佈問題之前在SO中進行更多搜索。看起來你的問題已經被問到過了。不需要複製那裏的信息。記住這個網站的重點。 – yarian 2013-03-05 07:33:28

回答

3

試試下面的代碼

editText.addTextChangedListener(new TextWatcher() { 

     public void onTextChanged(CharSequence s, int start, 
       int before, int count) { 

     } 

     public void beforeTextChanged(CharSequence s, int start, 
       int count, int after) { 
     } 

     public void afterTextChanged(Editable s) { 

      Character cr = s.toString().charAt(0); 
    if(Character.isLetter(cr)) 
     { 
     // do stuff here 
     } 
      else 
      { 
       // do stuff here 
      } 


     } 
    }); 
0
editText.addTextChangedListener(new TextWatcher() { 

      public void onTextChanged(CharSequence s, int start, 
        int before, int count) { 
          //check if 's' starts with an alphabet 
          if(Character.isLetter(s.toString().charAt(0))) 
          { 
            //success 
          } else { 
            //fail 
          } 
      } 

      public void beforeTextChanged(CharSequence s, int start, 
        int count, int after) { 
      } 

      public void afterTextChanged(Editable s) { 
      } 
     }); 
0

您可以使用方法chatAt(INT指數)在指定的位置得到字符的值,你的情況爲0。

那麼你應該使用isLetter()來驗證提取的字符是字母。

例如。 isLetter(chatAt(0))

相關問題