Skip to content Skip to sidebar Skip to footer

How To Add A Character In Edittext After User Starts Typing

I have an editText where a user inputs a phone number, but right when they click their first number, I want a '+' to appear in the beginning of the text. I have this code but the '

Solution 1:

Use TextWatcher

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

Implement it like this. You can also trick it to fit your needs

editText.setOnEditorActionListener(newTextView.OnEditorActionListener() {
    @OverridepublicbooleanonEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            // Specify your database function here.returntrue;
        }
        returnfalse;
    }
});

Alternatively, you can use the OnEditorActionListener interface to avoid the anonymous inner class.

Solution 2:

Patternp= Pattern.compile("^\\d+.*");

editText.addTextChangedListener(newTextWatcher() {

        @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
        }

        @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @OverridepublicvoidafterTextChanged(Editable s) {
            if (p.matcher(s.toString().trim()).matches()) {
                editText.setText(prefix + s.toString());
            }
            Selection.setSelection(editText.getText(), editText.getText().length());
        }
    });

Solution 3:

if (s.length == 1){ 
          if (s.toString().equals("+"))  editText.setText""else editText.setText("+"+s.toString)
          }

Post a Comment for "How To Add A Character In Edittext After User Starts Typing"