Skip to content

Instantly share code, notes, and snippets.

@repitch
Last active April 21, 2024 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save repitch/2ca5b01a842609cfe26f3a41f825a300 to your computer and use it in GitHub Desktop.
Save repitch/2ca5b01a842609cfe26f3a41f825a300 to your computer and use it in GitHub Desktop.
Android / custom editText that removes/restores hint on focus in/out
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.StringRes;
import android.util.AttributeSet;
import android.widget.EditText;
/**
* Edit text that removes hint when it is focused.
* If text is centered horizontally and hint is set, on some devices cursor can look ugly in the center of hint.
* So, this editText automatically hides hint when focus is on, and shows it back when focus is out
* <p>
* ! Important !
* Use {@link #setSavedHint(CharSequence)} instead of {@link #setHint(CharSequence)}
*
* @author repitch
*/
public class HintHideEditText extends EditText {
private CharSequence savedHint;
public HintHideEditText(Context context) {
super(context);
}
public HintHideEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HintHideEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (focused) {
savedHint = getHint();
}
validateHint(focused);
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
public CharSequence getSavedHint() {
return savedHint;
}
public void setSavedHint(CharSequence savedHint) {
this.savedHint = savedHint;
validateHint(hasFocus());
}
public void setSavedHint(@StringRes int resid) {
setSavedHint(getContext().getResources().getText(resid));
}
private void validateHint(boolean focused) {
setHint(focused ? "" : savedHint);
}
}
@hahien1989
Copy link

Bạn giúp tôi được không

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment