2016-11-18 87 views
-2

我做了一個代碼,用戶無法在字符串中輸入第一個空格。 允許用戶在最少2個字符後輸入空格。 我需要重新定義我的方法,所以用戶只輸入一次空白,並且只在兩個或多個字符後輸入一次。之後,它應該被阻止。我怎麼做?輸入一個字符串後,防止字符串中出現空格

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),返回false如果前兩個字符一個空白,算上所有的空格,返回false如果n> 1

+0

如何添加字母到這種模式 –

+0

\ S是事實上的字母/數字/等。它包含除空白之外的所有字符, – GoneUp

0

你需要做的是使用一個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

mTargetEditText.addTextChangedListener(new CustomWatcher()); 
0

您可以用TextWatcher控制你EDITTEXT(我認爲),你只需要檢查內部afterTextChanged(),如果長度爲< 2否則,如果字符串包含炭「」。

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; 
} 
相關問題