아직도 검색 중이라면 마지막 날에이 문제가 발생하여 TextWatcher을 사용하는 것이 가장 좋은 (여전히 좋지는 않은) 옵션이라는 것을 알았습니다. 나는 신용 카드 번호의 숫자를 그룹화해야했다.
신용 카드 번호에 대한 나의 서식 기능이처럼 보였다
someEditText.addTextChagedListener(new TextWatcher()
{
//According to the developer guide, one shall only edit the EditText's
//content in this function.
@Override
public void afterTextChanged(Editable text)
{
//You somehow need to access the EditText to remove this listener
//for the time of the changes made here. This is one way, but you
//can create a proper TextWatcher class and pass the EditText to
//its constructor, or have the EditText as a member of the class
//this code is running in (in the last case, you simply have to
//delete this line).
EditText someEditText = (EditText) findViewById(R.id.someEditText);
//Remove listener to prevent further call due to the changes we're
//about to make (TextWatcher is recursive, this function will be
//called again for every change you make, and in my experience,
//replace generates multiple ones, so a flag is not enough.
someEditText.removeTextChangedListener(this);
//Replace text with processed the processed string.
//FormatText is a function that takes a CharSequence (yes, you can
//pass the Editable directly), processes it the way you want, then
//returns the result as a String.
text.replace(0, text.length(), FormatText(text));
//Place the listener back
someEditText.addTextChangedListener(this);
}
@Override
public void beforeTextChaged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
});
:
String FormatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
for (int i = 0; i < text.length(); ++i)
{
if (Character.isDigit(text.charAt(i)))
{
//You have to be careful here, only add extra characters before a
//user-typed character, otherwise the user won't be able to delete
//with backspace, since you put the extra character back immediately.
//However, this way, my solution would put a space at the start of
//the string that I don't want, hence the > check.
if (count % 4 == 0 && count > 0)
formatted.append(' ');
formatted.append(text.charAt(i));
++count;
}
}
return formatted.toString();
}
이 솔루션은 실제로 글고의 내용 변경이있을 때마다 다시 작성하기 때문에 당신은뿐만 아니라 다른 문제에 신경해야 할 수도 있습니다 . 예를 들어, 직접 삽입 한 문자는 처리하지 말아야합니다 (즉, isDigit 검사의 추가 이유).