设计自定义TextView
,我想在TextView中删除文本前面的多余空白。
我尝试设置padding = 0dp
和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" />
答案 0 :(得分:1)
您应该使用自定义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" />
答案 1 :(得分:0)
您可以在XML布局中尝试includeFontPadding
属性:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:includeFontPadding="false"/>
在Java中为OR:
TextView textView = findViewById(R.idl.textview);
textView.setIncludeFontPadding(false);
文档: