Android 如何将文本对齐到 TextView 的顶部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1747196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:34:42  来源:igfitidea点击:

How to align the text to top of TextView?

androidlayout

提问by Riyaz Mohammed Ibrahim

How to align the text to top of a TextView?
Equivalent Android API for Swings setInsets()?
that is top of text should start be in (0,0) 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> 

I have used above snippet, however still output is not as expected
Any ideas?

我已经使用了上面的代码片段,但是输出仍然不符合预期有
什么想法吗?

回答by Kachi

So the space at the top of the TextView is padding used for characters outside the English language such as accents. To remove this space you can either set the android:includeFontPaddingattribute to falsein your XML or you can do it programmatically with the function setIncludeFontPadding(false).

因此,TextView 顶部的空间是用于填充英语之外的字符,例如重音符号。要删除此空间,您可以在 XML中将android:includeFontPadding属性设置为false,也可以使用该函数以编程方式执行此操作setIncludeFontPadding(false)

Look at the SDK documentation for TextViewif this is still unclear.

如果仍然不清楚,请查看 TextViewSDK 文档

EDITED ANSWER
If setting the android:includeFontPaddingattribute does not accomplish what you're trying to do, the other solution is to override the onDraw(Canvas canvas)method of the TextView that you're using so that it eliminates the additional top padding that Android adds to every TextView. After writing my original answer, I noticed that for some reason TextView includes extra padding in addition to the font padding. Removing the font padding as wellas this additional padding perfectly aligns the text to the top of the TextView. Look at the code snippet below.

编辑的答案
如果设置该android:includeFontPadding属性不能完成您要执行的操作,另一种解决方案是覆盖onDraw(Canvas canvas)您正在使用的 TextView的方法,以便消除 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();
    }
} 

回答by Ryan

The actual font itself has extra whitespace on the top and bottom I believe.

我相信实际的字体本身在顶部和底部有额外的空白。

Usually what I do is give the view negative margins. The issue is that this looks bad when devices come with different fonts.

通常我所做的是给视图负边距。问题是当设备带有不同的字体时,这看起来很糟糕。

android:layout_marginTop="-5dp"
android:layout_marginBottom="-5dp"

You will have to adjust based on the text size, bigger text sizes require more negative padding.

您必须根据文本大小进行调整,较大的文本大小需要更多的负填充。

回答by Terranology

In your .xml, write that:

在您的 .xml 中,写下:

android:gravity="center|top"

The first "center" align your line horizontally in the center and the next "top" align vertically up.

第一个“中心”在中心水平对齐您的线,下一个“顶部”垂直向上对齐。

回答by tse

Possible, you do not need make your view based on TextView. Try to extend View and write your text in onDraw().

可能,您不需要基于 TextView 创建您的视图。尝试扩展 View 并在onDraw().

Look at here: https://stackoverflow.com/a/32081250/1263771

看这里:https: //stackoverflow.com/a/32081250/1263771

回答by alex2k8

I think your snippet is right. I guess you are bothered by some pixels between top of the letter "T" and top edge of the TextView? This space is required to render some letters that are not present in English alphabet.

我认为你的片段是对的。我猜您是否对字母“T”顶部和 TextView 顶部边缘之间的一些像素感到困扰?需要此空间来呈现一些英文字母表中不存在的字母。

Check that links to get idea:

检查链接以获得想法:

回答by Vidar Vestnes

Im not sure if i understand what you are meaning, but the text inside the textview is going to be align to the top if you use gravity=top on the text-view.

我不确定我是否理解您的意思,但是如果您在文本视图上使用gravity=top,则文本视图中的文本将与顶部对齐。

If you put a backgrund color on you textview you might see better what is happening...

如果您在 textview 上添加背景颜色,您可能会更好地看到正在发生的事情......

I guess you problem is that the textview is centered since you use fill_parent on both height and width on the parent LinearLayout. The textview seems to be the only child so try putting gravity=top on the LinearLayout...

我猜您的问题是 textview 居中,因为您在父 LinearLayout 的高度和宽度上都使用了 fill_parent。textview 似乎是唯一的孩子,所以尝试将 Gravity=top 放在 LinearLayout 上...

Thats the only thing i could think of...

这是我唯一能想到的......