Phone number formatting an EditText in Android

前端 未结 14 913
情深已故
情深已故 2020-12-02 12:03

I am making a simple Address Book app (targeting 4.2) that takes name, address, city, state, zip and phone.

I want to format the phone number input as a phone number

相关标签:
14条回答
  • 2020-12-02 12:20

    There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...

    EditText text = (EditText) findViewById(R.id.editTextId);
    PhoneNumberUtils.formatNumber(text.getText().toString())
    

    ... to format your number in a standard format.

    PhoneNumberUtils.compare(String a, String b);
    

    ... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.

    p.s. setting the the EditText to phone is already a good choice; eventually it might be helpful to add digits e.g. in your layout it looks as ...

    <EditText
        android:id="@+id/editTextId"
        android:inputType="phone"
        android:digits="0123456789+" 
    /> 
    
    0 讨论(0)
  • 2020-12-02 12:21

    You can use a Regular Expression with pattern matching to extract number from a string.

        String s="";
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("(1111)123-456-789"); //editText.getText().toString()                                      
        while (m.find()) {
        s=s+m.group(0);
        }
        System.out.println("............"+s);    
    
        Output : ............1111123456789
    
    0 讨论(0)
  • 2020-12-02 12:21

    Don't worry. I have make a most of better solution for you. You can see this simple app link below.

    private EditText mPasswordField;
    public int textLength = 0;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mPasswordField = (EditText) findViewById(R.id.password_field);
        mPasswordField.addTextChangedListener(this);
    }
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    
        String text = mPasswordField.getText().toString();
        textLength = mPasswordField.getText().length();
    
        if (text.endsWith("-") || text.endsWith(" ") || text.endsWith(" "))
            return;
    
        if (textLength == 1) {
            if (!text.contains("(")) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
            }
    
        } else if (textLength == 5) {
    
            if (!text.contains(")")) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
            }
    
        } else if (textLength == 6) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
    
        } else if (textLength == 10) {
            if (!text.contains("-")) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
            }
        } else if (textLength == 15) {
            if (text.contains("-")) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
            }
        }else if (textLength == 18) {
            if (text.contains("-")) {
                mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                mPasswordField.setSelection(mPasswordField.getText().length());
            }
        } else if (textLength == 20) {
            Intent i = new Intent(MainActivity.this, Activity2.class);
            startActivity(i);
    
        }
    
    
    
    }
    
    @Override
    public void afterTextChanged(Editable s) {
    
    }
    

    Not: Don't forget "implement TextWatcher" with your activity class.

    Link :https://drive.google.com/open?id=0B-yo9VvU7jyBMjJpT29xc2k5bnc

    Hope you are feeling cool for this solution.

    0 讨论(0)
  • 2020-12-02 12:22

    You need to create a class:

    public class PhoneTextFormatter implements TextWatcher {
    
        private final String TAG = this.getClass().getSimpleName();
    
        private EditText mEditText;
    
        private String mPattern;
    
        public PhoneTextFormatter(EditText editText, String pattern) {
            mEditText = editText;
            mPattern = pattern;
            //set max length of string
            int maxLength = pattern.length();
            mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            StringBuilder phone = new StringBuilder(s);
    
            Log.d(TAG, "join");
    
            if (count > 0 && !isValid(phone.toString())) {
                for (int i = 0; i < phone.length(); i++) {
                    Log.d(TAG, String.format("%s", phone));
                    char c = mPattern.charAt(i);
    
                    if ((c != '#') && (c != phone.charAt(i))) {
                        phone.insert(i, c);
                    }
                }
    
                mEditText.setText(phone);
                mEditText.setSelection(mEditText.getText().length());
            }
        }
    
        @Override
        public void afterTextChanged(Editable s) {
    
        }
    
        private boolean isValid(String phone)
        {
            for (int i = 0; i < phone.length(); i++) {
                char c = mPattern.charAt(i);
    
                if (c == '#') continue;
    
                if (c != phone.charAt(i)) {
                    return false;
                }
            }
    
            return true;
        }
    }
    

    Use this as follows:

    phone = view.findViewById(R.id.phone);
    phone.addTextChangedListener(new PhoneTextFormatter(phone, "+7 (###) ###-####"));
    
    0 讨论(0)
  • 2020-12-02 12:22

    More like clean:

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    String text = etyEditText.getText();
        int textlength = etyEditText.getText().length();
    
        if (text.endsWith("(") ||text.endsWith(")")|| text.endsWith(" ") || text.endsWith("-")  )
                    return;
    
        switch (textlength){
            case 1:
                etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                etyEditText.setSelection(etyEditText.getText().length());
                break;
            case 5:
                etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                etyEditText.setSelection(etyEditText.getText().length());
                break;
            case 6:
                etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                etyEditText.setSelection(etyEditText.getText().length());
                break;
            case 10:
                etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                etyEditText.setSelection(etyEditText.getText().length());
                break;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-02 12:31

    Simply Use This :

    In Java Code :

    editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
    

    In XML Code :

    <EditText
        android:id="@+id/etPhoneNumber"
        android:inputType="phone"/>
    

    This code work for me. It'll auto format when text changed in edit text.

    0 讨论(0)
提交回复
热议问题