因此,TextView顶部的空格是用于英语以外的字符的填充,例如重音。要删除此空间,您可以将XML:includeFontPadding属性设置为false,或者使用函数setIncludeFontPadding(false)以编程方式进行设置。
编辑答复
如果设置android:includeFontPadding属性不能完成你想要做的事情,另一个解决方案就是覆盖你所使用的TextView的onDraw(Canvas canvas)方法,这样它就可以消除Android添加的额外的顶部填充到每个TextView。在写了我的原始答案之后,我发现由于某些原因,除了字体填充之外,TextView还包含额外的填充。删除字体填充以及这个额外的填充完全对齐文本到TextView的顶部。看下面的代码片段。
public class TopAlignedTextView extends TextView {
// Default constructor when inflating from XML file
public TopAlignedTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
// Default constructor override
public TopAlignedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
setIncludeFontPadding(false); //remove the font padding
setGravity(getGravity() | Gravity.TOP); //make sure that the gravity is set to the top
}
/*This is where the magic happens*/
@Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
//converts 5dip into pixels
int additionalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getContext().getResources().getDisplayMetrics());
//subtracts the additional padding from the top of the canvas that textview draws to in order to align it with the top.
canvas.translate(0, -additionalPadding);
if(getLayout() != null)
getLayout().draw(canvas);
canvas.restore();
}
}
去除Android TextView顶部填充实现文字顶部对齐
解决TextView顶部空格问题,可以设置XML属性`includeFontPadding`为`false`,或通过代码`setIncludeFontPadding(false)`移除。若此方法无效,可以自定义`TopAlignedTextView`类,覆盖`onDraw`方法,调整Canvas坐标以消除额外的顶部填充,实现文本完全对齐到顶部。
993

被折叠的 条评论
为什么被折叠?



