Android:如何根据可用空间设置文字

时间:2016-04-16 11:00:33

标签: android textview

我希望能够根据可用空间在TextView中设置文本,以避免椭圆化。

例如:

  • 如果有足够的空间设置文字"红狐狸跳跃"

  • 如果没有足够的空间(因此"红狐狸跳跃"将被椭圆化)设置文本"跳跃"

请问我该如何实现?

2 个答案:

答案 0 :(得分:1)

使用Paint对象绘制时,可以使用Paint.measureText(String)来确定整个字符串的宽度。如果该值大于TextView的宽度,那么我们知道文本将被省略。

float totalLength = myPaint.measureText("The red fox jumps");
float tvWidth = myTextView.getWidth(); // get current width of TextView

if (tvWidth < totalLength) { 
    // TextView will display text with an ellipsis
}

一旦我们知道文本将被截断,我们就可以使用反复试验来确定屏幕上可显示的最小文本是什么。此步骤将取决于您的业务逻辑,但应使用与第一步相同的Paint计算。

calculateStringWidth("The red fox jumps"); // too large
calculateStringWidth("red fox jumps"); // still too large
calculateStringWidth("fox jumps"); // width is less than TextView, will fit without ellipsis

答案 1 :(得分:1)

一种方法是计算给定文本的neede大小。

textView.setText("The red fox jumps");
// call measure is important here
textView.measure(0, 0);
int height = textView.getMeasuredHeight();
int width = textView.getMeasuredWidth();
if (height > availableHeight || width > availableWidth) {
    textView.setText("jumps");
}

measure()&#34;的调用确定了该视图及其所有子节点的大小要求&#34;。参考Androids View doc。 Documentation