Android EditText with suffix
I'm very new to Android development and have problems dealing with company projects. I need an EditText with a fixed suffix as part of EditText, so that when users input, the suffix will wrap to a new line like the normal content of EditText, but users can't edit and select this suffix
I searched everywhere and couldn't find a good solution to this problem. It was suggested to add a drawable containing text to the right of EditText, but when people type, this solution won't wrap the suffix part
Another possible solution is to handle the text changes of EditText, but this will make the handling of EditText cursor very complex (such as handle text hint and user selection gesture,...)
So my question is: does anyone implement this function, or can someone give me some guidance to easily implement this function for EditText
resolvent:
This is the dirty solution to your problem
Suppose you have an EditText named medittext, a string named suffix, and a Boolean addsuffix:
boolean addedSuffix = false;
String SUFFIX = " my suffix";
EditText mEditText = (EditText) findViewById(R.id.my_edit_text);
Attach textwatcher to your EditText
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// if the only text is the suffix
if(s.toString().equals(SUFFIX)){
mEditText.setText(""); // clear the text
return;
}
// If there is text append on SUFFIX as long as it is not there
// move cursor back before the suffix
if(s.length() > 0 && !s.toString().contains(SUFFIX) && !s.toString().equals(SUFFIX)){
String text = s.toString().concat(SUFFIX);
mEditText.setText(text);
mEditText.setSelection(text.length() - SUFFIX.length());
addedSuffix = true; // flip the addedSuffix flag to true
}
}
@Override
public void afterTextChanged(Editable s) {
if(s.length() == 0){
addedSuffix = false; // reset the addedSuffix flag
}
}
});
As I said, this is a fast and dirty solution, so the suffix is added only when the user actually types in the EditText field. If you need to add it before the user starts typing, you can modify the logic yourself
Good luck and happy coding!