I want to have constant text inside editText like:
http://<here_user_can_write>
User should not be able to delete any chars from "http://
", I searched about this and found this:
editText.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
}
});
but I don't know whether it restricts user to not delete any chars from start to end limit. I also could not understand use of Spanned class.
One way would be a good choice if we can put a TextView
inside EditText
but I don't think it is possible in Android since both are Views, is it possible?
I know I'm reviving an old post but I want to share with the community that I have struggled with this topic these days and I found that placing a
TextView
over theEditText
is not only perfectly doable (to respond to the second part of the question), much more in this case when the constant text is needed in the starting position, but preferable, too. Moreover the cursor won't even move before the "mutable" text at all, which is an elegant effect. I prefer this solution because it doesn't add workload and complexity to my app with listeners and whatsoever.Here's a sample code of my solution:
By enclosing the views in a
RelativeLayout
they will be overlapped. The trick here is playing with theandroid:paddingStart
property of theEditText
, to make the text start just right after theTextView
, whileandroid:layout_centerVertical="true"
andandroid:layout_marginStart="3dp"
properties of theTextView
make sure that its text is correctly aligned with text inputted and with the start of the underlying line of theEditText
(or at least this happens when using a Material themed one).That's how you can actually do it with an
InputFilter
:If you also want the prefix to be not selectable you can add the following code.
Here is a less efficient solution that should handle all cases for when characters OR words are deleted/inserted in OR around the prefix.
Code:
You can use it like this
I just found the solution how to make prefix not-editable and how to save text if you try to remove prefix. That's very close to @Rajitha Siriwardena answer. All you missed is to save text before any changes applied. It will be restored in afterTextChanged(...).
Code:
Did u try this method?