Preethi
Preethi

Reputation: 2152

format edit text as US phone number1(xxx)-xxxx you type in android?

I have been trying to find simple solution to format the phone number as user types . I do not want to use any library for formatting . Any ideas on how to do it ?

Upvotes: 1

Views: 2996

Answers (1)

sandrstar
sandrstar

Reputation: 12643

Seems you need to add TextChangedListener to your edit and prepare processing in there. Here's small example of inserting +7 in the beginning (actually, for - in the middle the logic stays the same, only another string operations needed):

/** Helper to control input phone number */
static class PrefixEntryWatcher implements TextWatcher {
    /** flag to avoid re-enter in {@link PhoneEntryWatcher#afterTextChanged(Editable)}*/
    private boolean isInAfterTextChanged = false;
    /** Prefix to insert */
    private final String prefix;
    /** Prefix to insert length */
    private final int prefixLength;
    /** Weak reference to parent text edit */
    private final WeakReference<EditText> parentEdit;

    /**
     * Default constructor
     *
     * @param prefix to be used for prefix
     */
    PrefixEntryWatcher(final String prefix, final EditText parentEdit) {
        this.prefix = prefix;
        this.prefixLength = (prefix == null ? 0 : prefix.length());
        this.parentEdit = new WeakReference<EditText>(parentEdit);
    }

    @Override
    public synchronized void afterTextChanged(final Editable text) {
       if (!this.isInAfterTextChanged) {
           this.isInAfterTextChanged = true;

           if (text.length() <= this.prefixLength) {
               text.clear();
               text.insert(0, this.prefix);

               final EditText parent = this.parentEdit.get();

               if (null != parent) {
                   parent.setSelection(this.prefixLength);
               }
           }
           else {
               if (!this.prefix.equals(text
                       .subSequence(0, this.prefixLength).toString())) {
                   text.clear();
                   text.insert(0, this.prefix);
               }

               final String withoutSpaces
                   = text.toString().replaceAll(" ", "");

               text.clear();
               text.insert(0, withoutSpaces);
           }

           // now delete all spaces
           this.isInAfterTextChanged = false;
       }
    }

    @Override
    public void beforeTextChanged(final CharSequence s,
            final int start,
            final int count,
            final int after) {
        // nothing to do here
    }

    @Override
    public void onTextChanged(final CharSequence s,
            final int start,
            final int before,
            final int count) {
        // nothing to do here
    }
}

It's not much code and logic, so seems no third party libraries are needed for this type of EditText handling.

Upvotes: 4

Related Questions