Пользовательский формат номера телефона (XXX-XXX-XXXX) TextWatcher зависает

Все работает: Формат (XXX-XXX-XXXX), который я хочу использовать в телефонном номере EditText, работает.

Проблема: при удалении символа "-" его нельзя удалить. Я застреваю.

введите здесь описание изображения

PhoneNumberTextWatcher.java

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

public class PhoneNumberTextWatcher implements TextWatcher {

    private static final String TAG = PhoneNumberTextWatcher.class
            .getSimpleName();
    private EditText edTxt;
    public boolean isDelete;

    public PhoneNumberTextWatcher(EditText edTxtPhone) {
        this.edTxt = edTxtPhone;
        edTxt.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.KEYCODE_DEL) {
                    isDelete = true;
                    LogUtils.Log_e("ISDELETE", String.valueOf(isDelete));
                }
                return false;
            }
        });
    }
l.substring(6, val.length());
            } else if (val.length() > 3 && val.length() < 6) {
                b = val.substring(3, val.length());
            }
            StringBuffer stringBuffer = new StringBuffer();
            if (a != null && a.length() > 0) {
                stringBuffer.append(a);
                if (a.length() == 3) {
                    stringBuffer.append("-");
                }
            }
            if (b != null && b.length() > 0) {
                stringBuffer.append(b);
                if (b.length() == 3) {
                    stringBuffer.append("-");
                }
            }
            if (c != null && c.length() > 0) {
                stringBuffer.append(c);
            }
            edTxt.removeTextChangedListener(this);
            edTxt.setText(stringBuffer.toString());
            edTxt.setSelection(edTxt.getText().toString().length());
            edTxt.addTextChangedListener(this);
        } else {
            edTxt.removeTextChangedListener(this);
            edTxt.setText("");
            edTxt.addTextChangedListener(this);
        }

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

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

    public void afterTextChanged(Editable s) {
        LogUtils.Log_e("ISDELETE", String.valueOf(isDelete));
        if (isDelete) {
            isDelete = false;
            return;
        }
        LogUtils.Log_e("ISDELETE", String.valueOf(isDelete));
        String val = s.toString();
        String a = "";
        String b = "";
        String c = "";
        if (val != null && val.length() > 0) {
            val = val.replace("-", "");
            if (val.length() >= 3) {
                a = val.substring(0, 3);
            } else if (val.length() < 3) {
                a = val.substring(0, val.length());
            }
            if (val.length() >= 6) {
                b = val.substring(3, 6);
                c = val.substring(6, val.length());
            } else if (val.length() > 3 && val.length() < 6) {
                b = val.substring(3, val.length());
            }
            StringBuffer stringBuffer = new StringBuffer();
            if (a != null && a.length() > 0) {
                stringBuffer.append(a);
                if (a.length() == 3) {
                    stringBuffer.append("-");
                }
            }
            if (b != null && b.length() > 0) {
                stringBuffer.append(b);
                if (b.length() == 3) {
                    stringBuffer.append("-");
                }
            }
            if (c != null && c.length() > 0) {
                stringBuffer.append(c);
            }
            edTxt.removeTextChangedListener(this);
            edTxt.setText(stringBuffer.toString());
            edTxt.setSelection(edTxt.getText().toString().length());
            edTxt.addTextChangedListener(this);
        } else {
            edTxt.removeTextChangedListener(this);
            edTxt.setText("");
            edTxt.addTextChangedListener(this);
        }

    }
}

Я пытаюсь TextWatcher использовать код ниже:

edtOrderCardPhone.addTextChangedListener(new PhoneNumberTextWatcher(edtOrderCardPhone));

См. соответствующий вопрос здесь. Может ли кто-нибудь помочь решить проблему!


person pRaNaY    schedule 23.02.2016    source источник


Ответы (2)


Я нашел решение изменить свой PhoneNumberTextWatcher, используя приведенный ниже код.

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class PhoneNumberTextWatcher implements TextWatcher {

    private static final String TAG = "PhoneNumberTextWatcher";
    private EditText editText;

    public PhoneNumberTextWatcher(EditText edTxtPhone) {
        this.editText = edTxtPhone;
    }

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

        if (before == 0 && count == 1) {  //Entering values

            String val = s.toString();
            String a = "";
            String b = "";
            String c = "";
            if (val != null && val.length() > 0) {
                val = val.replace("-", "");
                if (val.length() >= 3) {
                    a = val.substring(0, 3);
                } else if (val.length() < 3) {
                    a = val.substring(0, val.length());
                }
                if (val.length() >= 6) {
                    b = val.substring(3, 6);
                    c = val.substring(6, val.length());
                } else if (val.length() > 3 && val.length() < 6) {
                    b = val.substring(3, val.length());
                }
                StringBuffer stringBuffer = new StringBuffer();
                if (a != null && a.length() > 0) {
                    stringBuffer.append(a);

                }
                if (b != null && b.length() > 0) {
                    stringBuffer.append("-");
                    stringBuffer.append(b);

                }
                if (c != null && c.length() > 0) {
                    stringBuffer.append("-");
                    stringBuffer.append(c);
                }
                editText.removeTextChangedListener(this);
                editText.setText(stringBuffer.toString());
                if (cursorPosition == 3 || cursorPosition == 7) {
                    cursorPosition = cursorPosition + 2;
                } else {
                    cursorPosition = cursorPosition + 1;
                }
                if (cursorPosition <= editText.getText().toString().length()) {
                    editText.setSelection(cursorPosition);
                } else {
                    editText.setSelection(editText.getText().toString().length());
                }
                editText.addTextChangedListener(this);
            } else {
                editText.removeTextChangedListener(this);
                editText.setText("");
                editText.addTextChangedListener(this);
            }

        }

        if (before == 1 && count == 0) {  //Deleting values

            String val = s.toString();
            String a = "";
            String b = "";
            String c = "";

            if (val != null && val.length() > 0) {
                val = val.replace("-", "");
                if (cursorPosition == 3) {
                    val = removeCharAt(val, cursorPosition - 1, s.toString().length() - 1);
                } else if (cursorPosition == 7) {
                    val = removeCharAt(val, cursorPosition - 2, s.toString().length() - 2);
                }
                if (val.length() >= 3) {
                    a = val.substring(0, 3);
                } else if (val.length() < 3) {
                    a = val.substring(0, val.length());
                }
                if (val.length() >= 6) {
                    b = val.substring(3, 6);
                    c = val.substring(6, val.length());
                } else if (val.length() > 3 && val.length() < 6) {
                    b = val.substring(3, val.length());
                }
                StringBuffer stringBuffer = new StringBuffer();
                if (a != null && a.length() > 0) {
                    stringBuffer.append(a);

                }
                if (b != null && b.length() > 0) {
                    stringBuffer.append("-");
                    stringBuffer.append(b);

                }
                if (c != null && c.length() > 0) {
                    stringBuffer.append("-");
                    stringBuffer.append(c);
                }
                editText.removeTextChangedListener(this);
                editText.setText(stringBuffer.toString());
                if (cursorPosition == 3 || cursorPosition == 7) {
                    cursorPosition = cursorPosition - 1;
                }
                if (cursorPosition <= editText.getText().toString().length()) {
                    editText.setSelection(cursorPosition);
                } else {
                    editText.setSelection(editText.getText().toString().length());
                }
                editText.addTextChangedListener(this);
            } else {
                editText.removeTextChangedListener(this);
                editText.setText("");
                editText.addTextChangedListener(this);
            }

        }


    }

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

    public void afterTextChanged(Editable s) {


    }

    public static String removeCharAt(String s, int pos, int length) {

        String value = "";
        if (length > pos) {
            value = s.substring(pos + 1);
        }
        return s.substring(0, pos) + value;
    }
}

Спасибо B Bhanu Chander за решение.

person pRaNaY    schedule 23.02.2016
comment
Можно ли преобразовать это в xxx-xx-xx-xx-xx? - person IntoTheDeep; 20.07.2017

Вы можете сделать это следующим образом:

private EditText editText;

при создании():

editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

Снимок экрана:

введите здесь описание изображения

Надеюсь, что это поможет вам.

person Hiren Patel    schedule 23.02.2016
comment
Спасибо за повтор. Используя PhoneNumberFormattingTextWatcher() , я получаю XXXX XXX XXX этот формат. Но мой требуемый формат - XXX-XXX-XXXX . У меня уже есть решение, которое я разместил в качестве ответа. - person pRaNaY; 23.02.2016
comment
@pRaNaY, Нет, ты можешь найти тот же снимок экрана. - person Hiren Patel; 23.02.2016
comment
Я получил твой ответ. Но мое требование состоит в том, чтобы иметь собственный номер телефона с дефисом (-) после 3, 6 цифр в номере телефона, который я достиг с помощью своего кода. - person pRaNaY; 25.02.2016