[英]How to align the text to top of TextView?
如何将文本与TextView顶部对齐?
用于Swings setInsets()的等效Android API?
文本顶部应该从TextView的(0,0)开始
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="42sp"
android:paddingTop="0px"
android:gravity="top">
</TextView>
</LinearLayout>
我已经使用了上面的代码片段,但是仍然输出不是预期的
有任何想法吗?
因此,TextView顶部的空格是用于英语之外的字符的填充,例如重音。 要删除此空间,可以在XML中将android:includeFontPadding
属性设置为false
,也可以使用函数setIncludeFontPadding(false)
以编程方式执行此操作。
如果仍然不清楚,请查看TextView的SDK文档 。
编辑答案
如果设置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:layout_marginTop="-5dp"
android:layout_marginBottom="-5dp"
您必须根据文本大小进行调整,较大的文本大小需要更多的负填充。
在.xml中,写下:
android:gravity="center|top"
第一个“中心”将您的线水平对齐在中间,下一个“顶部”垂直对齐。
可能,您不需要基于TextView创建视图。 尝试扩展View并在onDraw()
编写文本。
我认为你的代码是正确的。 我猜你被字母“T”顶部和TextView顶边之间的一些像素所打扰? 此空间需要呈现一些英文字母不存在的字母。
检查链接以获取想法:
我不确定我是否理解你的意思,但如果你在文本视图中使用gravity = top,textview中的文本将与顶部对齐。
如果你在textview上添加背景颜色,你可能会看到更好的情况......
我猜你的问题是textview是居中的,因为你在父LinearLayout上的高度和宽度都使用了fill_parent。 textview似乎是唯一的孩子,所以尝试将gravity = top放在LinearLayout上......
这是我唯一能想到的......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.