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

前端 未结 14 2004
执笔经年
执笔经年 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:23

    I had the same problem. Attribute android:includeFontPadding="false" does not work for me. I've solved this problem in this way:

    public class TextViewWithoutPaddings extends TextView {
    
        private final Paint mPaint = new Paint();
    
        private final Rect mBounds = new Rect();
    
        public TextViewWithoutPaddings(Context context) {
            super(context);
        }
    
        public TextViewWithoutPaddings(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public TextViewWithoutPaddings(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onDraw(@NonNull Canvas canvas) {
            final String text = calculateTextParams();
    
            final int left = mBounds.left;
            final int bottom = mBounds.bottom;
            mBounds.offset(-mBounds.left, -mBounds.top);
            mPaint.setAntiAlias(true);
            mPaint.setColor(getCurrentTextColor());
            canvas.drawText(text, -left, mBounds.bottom - bottom, mPaint);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            calculateTextParams();
            setMeasuredDimension(mBounds.width() + 1, -mBounds.top + 1);
        }
    
        private String calculateTextParams() {
            final String text = getText().toString();
            final int textLength = text.length();
            mPaint.setTextSize(getTextSize());
            mPaint.getTextBounds(text, 0, textLength, mBounds);
            if (textLength == 0) {
                mBounds.right = mBounds.left;
            }
            return text;
        }
    }
    

提交回复
热议问题