如何查看TextView文本内容是否已被截断

ric*_*ard 11 android

我可以在布局xml文件中的TextView中设置最大行.在我的代码中,在我将setText()调用到TextView之后,如何查看文本内容是否已被截断(即文本是否超过最大行)?

谢谢.

Gre*_*lli 8

所以虽然我还没有测试过这个(抱歉没有在我面前设置sdk)

您的TextView应该为其创建一个Paint对象.现在我假设TextPaint已经使用正确的填充和偏移量构建了文本视图的背景图像.所以你应该能够做类似的事情

TextView a = getViewById(R.id.textview);
TextPaint paint = a.getPaint();
Rect rect = new Rect();
String text = String.valueOf(a.getText());
paint.getTextBounds(text, 0, text.length(), rect);
if(rect.height() > a.getHeight() || rect.width() > a.getWidth()) {
Log.i("TEST", "Your text is too large");
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我知道这是一个老问题,但我在搜索类似的答案时遇到了它,想要提供我找到的解决方案,万一其他人都在想.

这对我有用:

TextView myTextView = rootView.getViewById(R.id.my_text_view);
if (myTextView.getLineCount() > myTextView.getMaxLines()) {
  // your code here
}
Run Code Online (Sandbox Code Playgroud)