EditText社会安全号码

问题描述 投票:2回答:3

我正在为加州的android开发一个应用程序。现在我想以xxx-xx-xxxx格式输入编辑文本中的社会安全号码。我已经尝试使用以下代码来实现功能,但它不能正常清除文本..以下是我的代码。任何帮助,将不胜感激。我想要自动格式化功能。

etSocialSecurityNumber.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String text = etSocialSecurityNumber.getText().toString();
            textlength = etSocialSecurityNumber.getText().length();

            if(text.endsWith(" "))          
                return;


            if(textlength == 4 || textlength == 7 )
            {
                etSocialSecurityNumber.setText(new    StringBuilder(text).insert(text.length()-1, "-").toString());
                    etSocialSecurityNumber.setSelection(etSocialSecurityNumber.getText().length());
            }

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
android android-edittext
3个回答
6
投票

这将添加一个 - 在每4个字符之后并且它处理所有类型的用户编辑,只需将你的条件设置为3和2个字符:

    edit_text.addTextChangedListener(new TextWatcher() {

        private boolean spaceDeleted;

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

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

            CharSequence charDeleted = s.subSequence(start, start + count);
            spaceDeleted = " ".equals(charDeleted.toString());
        }

        public void afterTextChanged(Editable editable) {

            edit_text.removeTextChangedListener(this);

            int cursorPosition = edit_text.getSelectionStart();
            String withSpaces = formatText(editable);
            edit_text.setText(withSpaces);

            edit_text.setSelection(cursorPosition + (withSpaces.length() - editable.length()));


            if (spaceDeleted) {
                edit_text.setSelection(edit_text.getSelectionStart() - 1);
                spaceDeleted = false;
            }


            edit_text.addTextChangedListener(this);
        }

        private 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)))
                {
                    if (count % 4 == 0 && count > 0)
                        formatted.append("-");
                    formatted.append(text.charAt(i));
                    ++count;
                }
            }
            return formatted.toString();
        }
    });

编辑:

    userNameET.addTextChangedListener(new TextWatcher() {

        private boolean spaceDeleted;

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

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

            CharSequence charDeleted = s.subSequence(start, start + count);
            spaceDeleted = "-".equals(charDeleted.toString());
        }

        public void afterTextChanged(Editable editable) {

            userNameET.removeTextChangedListener(this);

            int cursorPosition = userNameET.getSelectionStart();
            String withSpaces = formatText(editable);
            userNameET.setText(withSpaces);

            userNameET.setSelection(cursorPosition + (withSpaces.length() - editable.length()));


            if (spaceDeleted) {
            //  userNameET.setSelection(userNameET.getSelectionStart() - 1);
                spaceDeleted = false;
            }


            userNameET.addTextChangedListener(this);
        }

        private String formatText(CharSequence text)
        {
            StringBuilder formatted = new StringBuilder();
            int count = 0;
            if(text.length()==3||text.length()==6)
            {
                if (!spaceDeleted)
                formatted.append(text+"-");
                else
                    formatted.append(text);
            }
            else
                formatted.append(text);
            return formatted.toString();
        }
    });

1
投票

我知道在这里发布答案为时已晚。我只是想分享我用来格式化SSN的代码。请尝试以下代码。

public class SSNFormatter implements TextWatcher{

private boolean mFormatting;

private boolean clearFlag;
private int mLastStart;
private String mBeforeText;

private boolean spaceDeleted;
WeakReference<EditText> mWeakEditText;

public SSNFormatter(WeakReference<EditText> weakEditText) {
    this.mWeakEditText = weakEditText;
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    mLastStart = start;
    mBeforeText = s.toString();
}

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

}

@Override
public void afterTextChanged(Editable s) {

    if (s.length()>0 && mWeakEditText.get().getText().hashCode() == s.hashCode() && mWeakEditText.get().getError() != null)
        mWeakEditText.get().setError(null);
    if (!mFormatting) {
        mFormatting = true;
        int curPos = mLastStart;
        String beforeValue = mBeforeText;
        String currentValue = s.toString();
        String formattedValue = formatSSN(s);
        if (currentValue.length() > beforeValue.length()) {
            int setCusorPos = formattedValue.length()
                    - (beforeValue.length() - curPos);
            mWeakEditText.get().setSelection(
                    setCusorPos < 0 ? 0 : setCusorPos);
        } else {
            int setCusorPos = formattedValue.length()
                    - (currentValue.length() - curPos);
            if (setCusorPos > 0
                    && !Character.isDigit(formattedValue
                    .charAt(setCusorPos - 1))) {
                setCusorPos--;
            }
            mWeakEditText.get().setSelection(
                    setCusorPos < 0 ? 0 : setCusorPos);
        }
        mFormatting = false;
    }

}

private String formatSSN(Editable text){
    StringBuilder formattedString = new StringBuilder();
    // Remove everything except digits
    int p = 0;
    while (p < text.length()) {
        char ch = text.charAt(p);
        if (!Character.isDigit(ch)) {
            text.delete(p, p + 1);
        } else {
            p++;
        }
    }

    // Now only digits are remaining
    String allDigitString = text.toString();

    int totalDigitCount = allDigitString.length();

    if (totalDigitCount == 0 || totalDigitCount > 10) {
        // May be the total length of input length is greater than the
        // expected value so we'll remove all formatting
        text.clear();
        text.append(allDigitString);
        return allDigitString;
    }
    int alreadyPlacedDigitCount = 0;

    // Only '1' is remaining and user pressed backspace and so we clear
    // the edit text.
    if (allDigitString.equals("1") && clearFlag) {
        text.clear();
        clearFlag = false;
        return "";
    }
    boolean chang3 = true;
    boolean chang2 = false;
    // There must be a '-' inserted after the next 3 numbers
    if (chang3 && totalDigitCount - alreadyPlacedDigitCount > 3) {
        formattedString
                .append(allDigitString.substring(alreadyPlacedDigitCount,
                        alreadyPlacedDigitCount + 3) + "-");
        alreadyPlacedDigitCount += 3;
        chang3 = false;
        chang2 = true;
    }

    // There must be a '-' inserted after the next 2 numbers
    if (chang2 && totalDigitCount - alreadyPlacedDigitCount > 2) {
        formattedString
                .append(allDigitString.substring(alreadyPlacedDigitCount,
                        alreadyPlacedDigitCount + 2) + "-");
        alreadyPlacedDigitCount += 2;
        chang3 = true;
        chang2 = false;
    }

    // All the required formatting is done so we'll just copy the
    // remaining digits.
    if (totalDigitCount > alreadyPlacedDigitCount) {
        formattedString.append(allDigitString
                .substring(alreadyPlacedDigitCount));
    }

    text.clear();
    text.append(formattedString.toString());
    return formattedString.toString();
}

}

1
投票

以下Kotlin代码足以满足我的要求

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        backspaced = count == 0
}


override fun afterTextChanged(s: Editable?) {
    s?.apply {
        if (!isEmpty()) {
            if (get(lastIndex) != '-' && (length > 1 && get(lastIndex - 1) != '-') && !backspaced)
                count { x -> x.isDigit() }.let { mapOf(3 to 3, 4 to 3, 5 to 6, 6 to 6)[it]?.let { index -> insert(index, "-") } }
            else if ((get(lastIndex) == '-'  && backspaced) || (lastIndexOf('-') in listOf(0,1,2,4,5,7,8,9,10)) )
                delete(length - 1, length)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.