代码之家  ›  专栏  ›  技术社区  ›  Vishal Pawar

如何减少textview开头的额外空间?

  •  -2
  • Vishal Pawar  · 技术社区  · 8 年前

    我尝试了设置 padding=0dp android:includefontpadding=“false” 但是仍然添加了一些空白。

    android:layout_width=“匹配父级” android:background=“fff” android:includefontpadding=“假” android:layout_height=“wrap_content”/>

    . android:includeFontPadding="false" 但还是增加了一些空白。

    <TextView
            android:layout_width="match_parent"
            android:text="LorenIP Some"
            android:textColor="#00FF00"
            android:background="#FFF"
            android:padding="0dp"    
            android:includeFontPadding="false"
            android:textSize="40dp"
            android:layout_height="wrap_content" />
    

    2 回复  |  直到 8 年前
        1
  •  1
  •   Mehdi Boutayeb    8 年前

        public class MyTextView extends AppCompatTextView {
    
        private final Paint mPaint = new Paint();
    
        private final Rect mBounds = new Rect();
    
        public MyTextView(Context context) {
            super(context);
        }
    
        public MyTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onDraw( 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;
        }
    }
    

    <com.example.TestApp.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LorenIP Some" />
    
        2
  •  0
  •   SamyB    8 年前

    includeFontPadding

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"/>
    

    TextView textView = findViewById(R.idl.textview);
    textView.setIncludeFontPadding(false);
    

    文件:

    setIncludeFontPadding

    includeFontPadding