如何减少额外的 space 出现在 TextView 的开始?

How to reduce extra space comes at start of TextView?

正在设计自定义 TextView,我想删除 TextView 中文本前面多余的白色 space。

我尝试设置 padding = 0dpandroid:includeFontPadding="false",但仍然添加了一些白色 space。

<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" />

您可以在 XML 布局中尝试 includeFontPadding 属性:

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

或 JAVA:

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

文档:

setIncludeFontPadding

includeFontPadding

您应该使用自定义 TextView 并覆盖 onDraw() 方法

    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;
    }
}

在Xml中使用这个

<com.example.TestApp.MyTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="LorenIP Some" />