android 文字顶部对齐,android – 如何将文本对齐到TextView的顶部?

去除Android TextView顶部填充实现文字顶部对齐
解决TextView顶部空格问题,可以设置XML属性`includeFontPadding`为`false`,或通过代码`setIncludeFontPadding(false)`移除。若此方法无效,可以自定义`TopAlignedTextView`类,覆盖`onDraw`方法,调整Canvas坐标以消除额外的顶部填充,实现文本完全对齐到顶部。
AI助手已提取文章相关产品:

因此,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();

}

}

您可能感兴趣的与本文相关内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值