Uniform text wrapping in TextView

前端 未结 6 1397
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 06:34

I need nice text wrapping in TextView, especially for text in headers.

Text wrapping for TextView might look like this, where the last word is in new line:



        
6条回答
  •  鱼传尺愫
    2021-01-19 07:31

    The algorithm would be roughly:

    1. calculate String width (with Paint.measureText or something)
    2. if it is less than container (TextView) width, just use it
    3. otherwise divide String width by container to know how many "\n" to enter
    4. with some search algorithm look for a space character the closest to 1/nth of the width (again using measureText if the font is not monospace)
    5. substring at that point and repeat point 4 for n-1 (n > 1)

    Probably will require some adjustments like using container width by some small percent smaller than real.

提交回复
热议问题