Aligning drawableLeft with text of button

后端 未结 14 1999
长情又很酷
长情又很酷 2021-01-30 06:41

Here is my layout:

\"enter

The issue I\'m facing is with the drawable checkmark. H

14条回答
  •  旧巷少年郎
    2021-01-30 07:05

    public class DrawableCenterTextView extends TextView {
    
        public DrawableCenterTextView(Context context, AttributeSet attrs,
                int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public DrawableCenterTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public DrawableCenterTextView(Context context) {
            super(context);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            Drawable[] drawables = getCompoundDrawables();
            if (drawables != null) {
                Drawable drawableLeft = drawables[0];
                Drawable drawableRight = drawables[2];
                if (drawableLeft != null || drawableRight != null) {
                    float textWidth = getPaint().measureText(getText().toString());
                    int drawablePadding = getCompoundDrawablePadding();
                    int drawableWidth = 0;
                    if (drawableLeft != null)
                        drawableWidth = drawableLeft.getIntrinsicWidth();
                    else if (drawableRight != null) {
                        drawableWidth = drawableRight.getIntrinsicWidth();
                    }
                    float bodyWidth = textWidth + drawableWidth + drawablePadding;
                    canvas.translate((getWidth() - bodyWidth) / 2, 0);
                }
            }
            super.onDraw(canvas);
        }
    }
    

提交回复
热议问题