Cause: Sometimes we need to display a mixed background hint when there is no text, so if the control overlay is inefficient, we can use the OnDraw method solution of overloaded view:
This is the effect, that 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;float TextSize = 0;int TextColor = 0xFF 000000;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 (). Getdisplaymetrics (). Density;searchsize = Mtypedarray.getdimension (r.styleable.searchedit_imagewidth, * density + 0.5F); TextColor = Mtypedarray.getcolor ( R.styleable.searchedit_textcolor, 0xff848484); textSize = MTYpedarray.getdimension (r.styleable.searchedit_textsize, + * density + 0.5F); mtypedarray.recycle ();} private void Initpaint () {paint = new paint (paint.anti_alias_flag);p Aint.setcolor (textcolor);p aint.settextsize ( textSize);} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas);D rawsearchicon (canvas);} private void Drawsearchicon (canvas canvas) {if (This.gettext (). toString (). Length () = = 0) {Float textWidth = paint.measure Text ("search"), float textHeight = getfontleading (paint), float dx = (getwidth ()-searchsize-textwidth-8)/2;float dy = (g Etheight ()-searchsize)/2;canvas.save (); Canvas.translate (GETSCROLLX () + DX, getscrolly () + dy); if (mdrawable! = null) { Mdrawable.draw (canvas);} Canvas.drawtext ("Search", getscrollx () + searchsize + 8, getscrolly () + (GetHeight ()-(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.serarch); 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;}}
[Android] Add graphics to edittext hint