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

Android:如何根据可用空间设置文本,android,textview,Android,Textview,我希望能够根据可用空间在TextView中设置文本,以避免省略 例如: 如果有足够的空间设置文本“红狐跳跃” 如果没有足够的空间(因此“红狐跳跃”将被省略),则设置文本“跳跃” 请告诉我如何才能做到这一点?当使用绘制对象绘制时,您可以使用它来确定整个字符串的宽度。如果该值大于TextView的宽度,则我们知道文本将被省略 float totalLength = myPaint.measureText("The red fox jumps"); float tvWidth = myTextVi

我希望能够根据可用空间在TextView中设置文本,以避免省略

例如:

  • 如果有足够的空间设置文本“红狐跳跃”

  • 如果没有足够的空间(因此“红狐跳跃”将被省略),则设置文本“跳跃”

请告诉我如何才能做到这一点?

当使用绘制对象绘制时,您可以使用它来确定整个字符串的宽度。如果该值大于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
}

一种方法是计算给定文本的需求大小

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()的调用“确定此视图及其所有子视图的大小要求”。参考Androids视图文档

回答得好!measureText是否返回像素宽度?我相信是的,大多数Android API都返回像素。
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");
}