Last active
April 21, 2024 11:07
-
-
Save repitch/2ca5b01a842609cfe26f3a41f825a300 to your computer and use it in GitHub Desktop.
Android / custom editText that removes/restores hint on focus in/out
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bạn giúp tôi được không