如何在Android中计算包含具有特定高度的TextView的行高?

Sag*_*Low 6 height android textview android-layout

我想计算(或布局)高度(在DP中),它只包含使用默认行间距时的TextView结果TextView text size
这个布局的IE:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/minRow1col1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textIsSelectable="false"
        android:textSize="11dp" />  

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

布局/线高是多少?(任何公式?我不需要运行时的值)

谢谢 !

jfc*_*ato 10

我不知道这对你们有什么帮助,但我的解决方案是获得一条线的高度它与布局的高度无关,只需采用这样的字体指标:

myTextView.getPaint().getFontMetrics().bottom - myTextView.getPaint().getFontMetrics().top)
Run Code Online (Sandbox Code Playgroud)

有了这个,你就可以获得行高,对我来说,它适用于所有单词(有一些像"g"或"j"的字符占用一些底部空间,所谓的"下行"等等).


Dee*_*eeV 5

尝试使用TextPaint的对象TextView

TextView tv = useTextView;
String text = tv.getText().toString();
Paint textPaint = tv.getPaint();

Rect textRect = new Rect();
textPaint.getTextBounds(text, 0, text.length(), textRext);

int textHeight = textRect.height();
Run Code Online (Sandbox Code Playgroud)

根据以下文档Paint#getTextBound

返回边界(由调用者分配)包围所有字符的最小矩形,隐含原点位于 (0,0)。

使用所使用的Paint对象TextView将确保它具有将用于绘制文本的相同参数集。


Pul*_*ull 0

您可以尝试Paint.getTextBounds()

String finalVal ="Hello";

Paint paint = new Paint();
paint.setTextSize(18);  
paint.setTypeface(Typeface.SANS_SERIF);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);

Rect result = new Rect();
// Measure the text rectangle to get the height
paint.getTextBounds(finalVal, 0, finalVal.length(), result);

Log.d("WIDTH        :", String.valueOf(result.width()));
Log.d("HEIGHT       :", String.valueOf(result.height()));
Run Code Online (Sandbox Code Playgroud)

来源