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

时间:2010-05-20 17:07:34

标签: android

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

谢谢。

3 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:5)

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

这对我有用:

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

答案 2 :(得分:2)

试试这个:

mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        ViewTreeObserver obs = mTextView.getViewTreeObserver();
        obs.removeOnGlobalLayoutListener(this);
        int height = mTextView.getHeight();
        int scrollY = mTextView.getScrollY();
        Layout layout = mTextView.getLayout();
        int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
        int lastVisibleLineNumber = layout.getLineForVertical(height + scrollY);

        //check is latest line fully visible
        if (mTextView.getHeight() < layout.getLineBottom(lastVisibleLineNumber)) {
            // TODO you text is cut
        }
    }
});