Check if textview is ellipsized in android

后端 未结 3 1472
误落风尘
误落风尘 2020-12-06 05:15

I have TextView with width as wrap content. In this TextView I set text, but text is not of the same length every time. When text is v

3条回答
  •  再見小時候
    2020-12-06 05:36

    Using getEllipsisCount wont 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 textView is too long or not. The textview 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.

提交回复
热议问题