0

I want to add a prefilled text like country code in an edittext for mobile number. Prefilled text should be uneditable. I have tried it by overriding onSelectionChanged(). Is there any better solution?

    final EditText editText = new EditText(this){
        int prevSelection;
        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if(selStart < 4){
                setSelection(prevSelection);
                return;
            }
            prevSelection = selStart;
        }
    };
Kamal
  • 51
  • 1
  • 5

4 Answers4

0

Is this what you want?

editText.setText("This is a prefilled text"); // This to set prefilled text
editText.setFocusable(false);                 // This disable editing

OR

editText.setHint("This is sample country code"); // this is the hint

Hint is something like this:

enter image description here

cw fei
  • 1,534
  • 1
  • 15
  • 33
0

try this

final EditText editText = new EditText(this){
        int prevSelection;
        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if (!editText.getText().toString().startsWith("pre filled text")){
                editText.setText("pre filled text" + editText.getText().toString());
            }

        }
    };

The function will check if the EditText start with the "preFilled" text, if not it will add it to the beginning of the EditText

Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23
0

Implement android.text.TextWatcher in the Activity or Fragment containing the EditText.

In the afterTextChanged method add the country code to the beginning of the text.

It would be good to check if the country code is already filled in before adding it. Be careful not to end in an infinite loop here.

miva2
  • 2,111
  • 25
  • 34
0

Try to use this:

 editText.setText("country code" + editText.getText().toString());
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Gourav Samre
  • 134
  • 1
  • 7