I have a hint ("Name") and the underline covers the length of the hint, but when I start typing the underline doesn't follow the length of what I'm typing if it's shorter than the hint. I was wondering if there was a way to change the length of the underline?
[
][
]3
This code should make what you want:
final EditText editText = (EditText) findViewById(R.id.edit_query);
final CharSequence rememberHint = editText.getHint();
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (!b && TextUtils.isEmpty(editText.getText())) {
editText.setHint(rememberHint);
} else {
editText.setHint("");
}
}
});
I use a hack, so, when we focus on our edittext, or unfocus it, but it's not empty, we clear hint from it, and then, when we unfocus it and it's empty, we place hint back.
UPDATED
Also you can add text watcher to return hint on its place, when you cleared all text, but no unfocus from it:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() != 0) {
editText.setHint("");
} else {
editText.setHint(rememberHint);
}
}
});
This addition to answer will provide more default behavior from user perspective.