[Android] Add a text hint to EditText
Cause: Sometimes we need to display a text-and-image background prompt when there is no text. At this time, if the control overlay method is used, the efficiency will be very low, therefore, we can use the onDraw solution of the overload View:
This is the effect, the search box.
Package com. finals. teltem. view; import android. content. context; import android. content. res. typedArray; import android. graphics. canvas; import android. graphics. paint; import android. graphics. paint. fontMetrics; import android. graphics. drawable. drawable; import android. util. attributeSet; import android. widget. editText; import com. finals. teltem. r; public class SearchView extends EditText {float searchSize = 0; fl Oat textSize = 0; int textColor = 0xFF000000; Drawable mDrawable; Paint paint; public SearchView (Context context, AttributeSet attrs) {super (context, attrs); InitResource (context, attrs ); initPaint ();} private void InitResource (Context context, AttributeSet attrs) {TypedArray mTypedArray = context. obtainStyledAttributes (attrs, R. styleable. searchedit); float density = context. getResources (). getDisplayMetri Cs (). density; searchSize = mTypedArray. getDimension (R. styleable. searchedit_imagewidth, 18 * density + 0.5F); textColor = mTypedArray. getColor (R. styleable. searchedit_textColor, 0xFF848484); textSize = mTypedArray. getDimension (R. styleable. searchedit_textSize, 14 * density + 0.5F); mTypedArray. recycle ();} private void InitPaint () {paint = new Paint (Paint. ANTI_ALIAS_FLAG); paint. setColor (textColor); paint. se TTextSize (textSize) ;}@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); DrawSearchIcon (canvas);} private void DrawSearchIcon (Canvas canvas) {if (this. getText (). toString (). length () = 0) {float textWidth = paint. measureText ("Search"); float textHeight = getFontLeading (paint); float dx = (getWidth ()-searchSize-textWidth-8)/2; float dy = (getHeight () -searchSize)/2; canvas. save (); c Anvas. translate (getScrollX () + dx, getScrollY () + dy); if (mDrawable! = Null) {mDrawable. draw (canvas);} canvas. drawText ("Search", getScrollX () + searchSize + 8, getScrollY () + (getHeight ()-textHeight)/2)-paint. getFontMetrics (). bottom-dy, paint); canvas. restore () ;}@ Overrideprotected void onAttachedToWindow () {super. onAttachedToWindow (); if (mDrawable = null) {try {mDrawable = getContext (). getResources (). getDrawable (com. finals. teltem. r. drawable. serarc H); mDrawable. setBounds (0, 0, (int) searchSize, (int) searchSize);} catch (Exception e) {}}@ Overrideprotected void onDetachedFromWindow () {if (mDrawable! = Null) {mDrawable. setCallback (null); mDrawable = null;} super. onDetachedFromWindow ();} public float getFontLeading (Paint paint) {FontMetrics fm = paint. getFontMetrics (); return fm. bottom-fm. top ;}}