How do I tell if my textview has been ellipsized?

前端 未结 14 1647
天涯浪人
天涯浪人 2020-11-30 19:31

I have a multi-line TextView that has android:ellipsize=\"end\" set. I would like to know, however, if the string I place in there is actually too

14条回答
  •  隐瞒了意图╮
    2020-11-30 20:05

    Using getEllipsisCount won't work with text that has empty lines within it. I used the following code to make it work :

    message.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
    
                if(m.isEllipsized == -1) {
                    Layout l = message.getLayout();
                    if (message.getLineCount() > 5) {
                        m.isEllipsized = 1;
                        message.setMaxLines(5);
                        return false;
                    } else {
                        m.isEllipsized = 0;
                    }
                }
                return true;
            }
        });
    

    Make sure not to set a maxLineCount in your XML. Then you can check for the lineCount in your code and if it is greater than a certain number, you can return false to cancel the drawing of the TextView and set the line count as well as a flag to save whether the text view is too long or not. The text view will draw again with the correct line count and you will know whether its ellipsized or not with the flag.

    You can then use the isEllipsized flag to do whatever you require.

提交回复
热议问题