Ellipsize 对于具有任意最大高度的多行 TextView 无法正常工作 [英] Ellipsize not working properly for a multiline TextView with an arbitrary maximum height
问题描述
我有一个最大高度未知的 TextView
,这取决于设备的 DPI/屏幕分辨率.因此,例如,在 MDPI 设备上,这个最大高度使得一次只能显示 2 行成为可能,这个值可以增加到一个未定义的数字.
I have a TextView
with an unknown maximum height, which is dependent on the device's DPI/screen resolution. So, for instance, on and MDPI device this maximum height makes it possible to show only 2 lines at a time, a value that can be increased up to an undefined number.
我的问题与 ellipsize 功能有关.假设某个设备允许显示 4 行.如果我手动设置最大行数,像这样...
My issue is related with the ellipsize functionality. Let's suppose that a certain device allows for 4 lines to be displayed. If I manually set the maximum number of lines, like this...
<TextView
android:id="@+id/some_id"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:ellipsize="end"
android:maxLines="4"
android:singleLine="false"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="This is some really really really really really long text"
android:textSize="15sp" />
...一切正常.如果文本不合适,则在第四行末尾添加省略号,如下所示:
...everything works OK. If the text doesn't fit properly, then the ellipsis are added at the end of the fourth line, like this:
This is some
really really
really really
really long...
但我宁愿不将行数设置为静态变量,因为我更愿意支持 DPI/屏幕分辨率的任意组合.因此,如果我删除 maxLines
省略号将不再正确显示在第四行,而是显示不完整的文本部分:
But I'd rather not set the number of lines as a static variable, as I would prefer to include support for any combination of DPI/screen resolution. So if I remove maxLines
the ellipsis is no longer correctly shown at line four, showing instead an incomplete portion of text:
This is some
really really
really really
really long
如果我稍微增加 TextView
的大小,我可以看到其余的文本仍在其他 Views
的后面"绘制.设置变量 maxHeight
似乎也不起作用.
If I slightly increase the TextView
size, I can see that the rest of the text is still being drawn "behind" the other Views
. Setting the variable maxHeight
doesn't seem to work either.
我似乎真的找不到这个问题的解决方案.有任何想法吗?如果有帮助,我只使用 Android v4.0.3 及更高版本(API 级别 15).
I really can't seem to find a solution for this issue. Any ideas? If it helps, I'm working only with Android v4.0.3 and up (API level 15).
推荐答案
用 TextView#getHeight()
和 TextView 计算
.然后调用 TextView
有多少行#getLineHeight()TextView#setMaxLines()
.
Calculate how many lines fit into the TextView
with TextView#getHeight()
and TextView#getLineHeight()
. Then call TextView#setMaxLines()
.
ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int maxLines = (int) textView.getHeight()
/ textView.getLineHeight();
textView.setMaxLines(maxLines);
textView.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
});
这篇关于Ellipsize 对于具有任意最大高度的多行 TextView 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!