How to remove the top and bottom space on textview of Android

前端 未结 14 1932
执笔经年
执笔经年 2020-11-28 04:58

When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bot

14条回答
  •  醉梦人生
    2020-11-28 05:41

    public class TopAlignedTextView extends TextView {
    
        public TopAlignedTextView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public TopAlignedTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs);
            setIncludeFontPadding(false); //remove the font padding
            setGravity(getGravity() | Gravity.TOP);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            TextPaint textPaint = getPaint();
            textPaint.setColor(getCurrentTextColor());
            textPaint.drawableState = getDrawableState();
            canvas.save();
    
            //remove extra font padding
            int yOffset = getHeight() - getBaseline();
            canvas.translate(0, - yOffset / 2);
    
            if (getLayout() != null) {
                getLayout().draw(canvas);
            }
            canvas.restore();
        }
    }
    

提交回复
热议问题