2016-11-18 11 views
-2

文字列に最初のスペースを入力できないコードを作成しました。 ユーザは、最小2文字後に空白文字を入力することができます。 私はメソッドを再定義する必要があるので、ユーザーが空白を一度入力し、2つ以上の文字の後に1回だけ入力します。その後、それは防ぐ必要があります。それ、どうやったら出来るの?1文字入力後に文字列内の空白を防ぐ

case UPDATE_NAME: 
 
\t  if (firstName.getText().toString().startsWith(" ")) 
 
\t \t firstName.setText(firstName.getText().toString().trim()); 
 

 
\t  if (firstName.getText().toString().contains(" ")) 
 
\t \t firstName.setText(firstName.getText().toString().replace(" ", " ")); 
 

 
\t  int indexOfSpace = firstName.getText().toString().lastIndexOf(" "); 
 
\t  if (indexOfSpace > 0) { 
 
\t \t String beforeSpace = firstName.getText().toString().substring(0, indexOfSpace); 
 
\t \t String[] splitted = beforeSpace.split(" "); 
 
\t \t if (splitted != null && splitted.length > 0) { 
 
\t \t  if (splitted[splitted.length - 1].length() < 2) 
 
\t \t \t firstName.setText(firstName.getText().toString().trim()); 
 
\t \t } 
 
\t  }

答えて

1

正規表現patternを使用してください。私はmade oneあなたの要件に一致する必要があります。

\S{2}\S*\s\S*\n 

Explanation: 
\S{2} two non whitespace 
\S* n non whitespace 
\s a whitespace 
\S* n non whitespace 
\n newline (i only added that for regexr, you may not need it) 

代替方法:String.charAt(int)以上 反復、最初の2つの文字で空白がある場合はfalseを返し、すべての空白を数え、あなたがする必要がどのようなn>は1

+0

は、どのように私はS \ –

+0

は/ etcアルファベット/数字をデファクトされ、このパターンにアルファベットを追加します。空白を除いてすべての文字が含まれていますが、 – GoneUp

0

が使用される場合にはfalseを返しますTextWatcher

public class CustomWatcher implements TextWatcher { 

private String myText; 
private int count = 0; 

@Override 
public void beforeTextChanged(CharSequence s, int start, int count, int after){ 
    myText= s; 
} 

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

} 

@Override 
public void afterTextChanged(Editable s) { 
    //check if there is a space in the first 2 characters, if so, sets the string to the previous before the space 
    if(s.length() < 3 && s.contains(" ")) 
     s= myText; 

    //if the length is higher than 2, and the count is higher than 0 (1 space added already), puts the string back if a space is entered 
    else if(s.contains(" ") && count > 0) 
     s= myText; 

    //If none of the above is verified and you enter a space, increase count so the previous if statement can do its job 
    else if(s.contains(" ")) 
     count++; 

} 

}

そして、あなたのEditText

に設定長さが2 <であれば、他の文字列は、文字を「」含まれている場合
mTargetEditText.addTextChangedListener(new CustomWatcher()); 
0

あなたはTextWatcherであなたのEditTextを(私は仮定)を制御することができ、あなただけ)(afterTextChangedの中身をチェックする必要があります。

1

この方法では、あなたの要件を満たす必要があります。

private static boolean isValidFirstName(String firstName) { 
    if (firstName != null && !firstName.startsWith(" ")) { 
     int numberOfSpaces = firstName.length() - firstName.replace(" ", "").length(); 
     if (firstName.length() < 2 || numberOfSpaces <= 1) { 
      return true; 
     } 
    } 
    return false; 
} 
関連する問題