4

So I have an extended TextView that I'm trying to create a StaticLayout from so that I can detect if the text is going off-screen by calling getEllipsisCount.

So from within the TextView I'm constructing the staticlayout like so:

layout = new StaticLayout(getText(), getPaint(), getWidth(), Alignment.ALIGN_NORMAL, 0f, 0f, false);

But even though layout.getLineCount() returns the correct number of lines, getEllipsisCount(n) never returns > 0, even when I can clearly see it adding ellipsis.

So I'm guessing this has become a not-good way to detect if text has gone off the screen... so does anyone know of a more appropriate way, or how to get this to work?

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
Nathan Fig
  • 14,970
  • 9
  • 43
  • 57
  • Could it be that the StaticLayout needs to be drawn first? Is there a way to draw just to test for ellipsis, without showing the user? – Nathan Fig Feb 28 '11 at 14:52
  • Where you able to determine if a textview was ellipse-ized? – sgarman Nov 10 '11 at 22:38
  • No, I believe the text has to be drawn before a valid value will be returned. But I originally asked this in order to create a solution to another question, see if what you need is there: http://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds – Nathan Fig Nov 11 '11 at 03:58
  • 3
    It happened to me when the text contained line breaks. Removing them fixed the elipsis computation. – Blackhex Jul 25 '14 at 17:56

1 Answers1

2

I also encountered this problem, on Android 4.2.2. I was able to get around it by using the ViewTreeObserver API to set a callback for the onGlobalLayout event and launching a delayed runnable from there:

ViewTreeObserver observer = _someView.getViewTreeObserver();    
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 
                @Override    
                public void onGlobalLayout() {
                  _somView.getViewTreeObserver().removeGlobalOnLayoutListener(this);    
                  _textView.postDelayed(new Runnable() {  
                       public void run() {
                          // Code that uses ellipsis detection here
                       }
                    }, 10); 
                });

This is admittedly somewhat hackish, but it's the only way I could get the ellipsis to be correctly detected, otherwise it just kept reporting that no ellipsisification was taking place. In my testing the delay is essential for this to work, but the whole thing executes quickly enough so that elements can be hidden/shown based on this information without the ui flickering.

Amos Joshua
  • 1,601
  • 18
  • 25