Skip to content Skip to sidebar Skip to footer

How To Put Hyphen Automatically Between Contact Number In Edittext In Android

I want to add hyphen in between contact umber automatically when user enters it at runtime & also it should remove it automaticaly, like 904-149-0646 i'm using this code, packa

Solution 1:

Try to follow this code..

@Override
public void afterTextChanged(Editable text) {
    if (isFormatting)
        return;

    isFormatting = true;

    // If deleting hyphen, also delete character before or after it
    if (deletingHyphen && hyphenStart > 0) {
        if (deletingBackward) {
            if (hyphenStart - 1 < text.length()) {
                text.delete(hyphenStart - 1, hyphenStart);
            }
        } else if (hyphenStart < text.length()) {
            text.delete(hyphenStart, hyphenStart + 1);
        }
    }
    if (text.length() == 3 || text.length() == 7) {
        text.append('-');
    }

    isFormatting = false;
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    if (isFormatting)
        return;

    // Make sure user is deleting one char, without a selection
    final int selStart = Selection.getSelectionStart(s);
    final int selEnd = Selection.getSelectionEnd(s);
    if (s.length() > 1 // Can delete another character
            && count == 1 // Deleting only one character
            && after == 0 // Deleting
            && s.charAt(start) == '-' // a hyphen
            && selStart == selEnd) { // no selection
        deletingHyphen = true;
        hyphenStart = start;
        // Check if the user is deleting forward or backward
        if (selStart == start + 1) {
            deletingBackward = true;
        } else {
            deletingBackward = false;
        }
    } else {
        deletingHyphen = false;
    }
}

Post a Comment for "How To Put Hyphen Automatically Between Contact Number In Edittext In Android"