3

I am using the following snippet in a code that checks if a string is small enough to fit inside a textview.

private int findLengthThatFits (TextView view, String text) {
    float textWidth = view.getPaint().measureText(text);
    if (textWidth >= view.getMeasuredWidth ()){
      //do somethings
    }
    //other stuff
}

But view.getMeasuredWidth () keeps returning 0.0. Does anyone know how I might fix this problem? I used How to find android TextView number of characters per line? as reference.

Community
  • 1
  • 1
learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

0

I faced this same problem a while back. In my case I was trying to count the number of lines the textview had taken. The problem was that methods like view.getMeasuredWidth () can only be used after requestLayout() is called on the textview. For solving this viewtreeobserver is used to ensure that methods are called only at appropriate time. I didnot want to use this so instead I used Ellipsizing Textview from this post. It worked like a charm and also has an interface to know if the provided text was ellipsized.

Community
  • 1
  • 1
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61