Sometimes we have to put constant non-editable text in EditText in Android. For example, when we have to take phone number as input we can put fix country code as a prefix. In the case of website address as input, we can put “https://” as hardcoded string at the start. For this purpose, you can use the following method in Java.
public static void AddConstantTextInEditText(EditText edt, String text) { edt.setText(text); Selection.setSelection(edt.getText(), edt.getText().length()); edt.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if(!s.toString().startsWith(text)){ edt.setText(text); Selection.setSelection(edt.getText(), edt.getText().length()); } } }); }
You can just pass your EditText object and a String to this method as shown in the following code.
EditText etWebsite = findViewById(R.id.et_website); AddConstantTextInEditText(etWebsite, "https://");
How it Works?
This method adds a TextChangedListener
to the EditText
and if the prefix text is removed it automatically adds it again.
That’s it 🙂
For other helping material, have a look at our Tutorials List.