Label in a editbox in android

前端 未结 9 2287
渐次进展
渐次进展 2020-12-14 10:41

My question is, how to put a label in a editBox in android ?

Like for example, i want to put \"To:\" in editbox of a contact picke

9条回答
  •  执笔经年
    2020-12-14 11:19

    I give you two ideas to do this :

    If you only need this in a couple of places, you can use a FrameLayout / merge to have a TextView over your EditText. Then using a padding on the edit text, you can make it seem like the TextView is "inside" the EditText. :

    
    
        
    
            
        
    
        
    
    

    Else you can inplement your own version of EditText, by writing your own Class. Here's a basic example, you'd need to tweak it a little :

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.text.TextPaint;
    import android.util.AttributeSet;
    import android.widget.EditText;
    
    public class LabelledEditText extends EditText {
    
        public LabelledEditText(Context context) {
            super(context);
            mPaddingLeft = getPaddingLeft();
        }
    
        public LabelledEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            mPaddingLeft = getPaddingLeft();
        }
    
        protected void onDraw(Canvas canvas) {
            TextPaint textPaint = getPaint();
            Rect size = new Rect();
            textPaint.getTextBounds(mLabel, 0, mLabel.length(), size);
            setPadding(mPaddingLeft + size.width(), getPaddingTop(), getPaddingRight(), getPaddingBottom());
            super.onDraw(canvas);
    
            canvas.drawText(mLabel, mPaddingLeft + size.left, size.bottom + getPaddingTop(), textPaint);
        }
    
    
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    
        private String mLabel = "To :  ";
        private int mPaddingLeft;
    
    }
    

提交回复
热议问题