2016-06-27 45 views
0

我们使用TableViews的ExpandableList在一侧显示包含行号的文本块。首先,将给定段落的字符串设置到TableView的右列中的文本视图中。然后,根据段落字符串和起始行号生成行号字符串。例如,从字符串(以1:1的起始行号):检测TextView是否包装一行

Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
Donec ultricies a nunc sit amet venenatis. 
Aenean placerat dictum nunc, 
nec pulvinar arcu consequat a. 
Proin dignissim velit ut augue dictum ultricies. 
Fusce lorem dolor, elementum id tempor at, 
pellentesque eu dolor. Vestibulum rhoncus 
arcu in sapien sagittis gravida. 
Nullam vel nisl enim. 
Maecenas scelerisque at quam non congue. 
Nullam quis porttitor purus, nec interdum tellus. 

产生下面的行号字符串:

\n\n\n\n5.\n\n\n\n\n10.\n\n 

此字符串然后放置在TableView中的最左边的列以每五行显示字符串的行号。

但是,当文本大小上升到文本行被打包的点(因为行太大而不适合屏幕)时出现问题。发生这种情况时,似乎需要在文本包装的网站的行号字符串中插入另一个\ n,以便将可能的多行包装文本统计为一行。因此,无论如何,对于android来检测一行是否被包装在TextView中,以便程序可以知道在行号字符串中插入\ n并补偿换行符?

回答

0

首先,您可以计算字符串渲染所需的屏幕宽度。将其与您的总设备/视图进行比较,检查是否需要为文本换行插入'\ n'。

PS:代码没有测试,但应该工作。如果您使用自定义字体,则可以用您自己的字体替换Typeface.DEFAULT。

public float computeTotalWidthOnScreen(String text) { 
     final Typeface typeface = Typeface.DEFAULT; 
     final Paint paint = new Paint(); 
     final Rect bounds = new Rect(); 
     paint.setTypeface(typeface); 
     paint.setAntiAlias(true); 
     paint.setTextSize(defaultFontSize); 
     paint.getTextBounds(text, 0, text.length(), bounds); 

     return bounds.width(); 
    } 
+0

无论何时我尝试使用textView的getWidth()方法,它将返回1300,而函数返回200-300范围内的文本值。然而,这条线仍然包装。你知道这是为什么吗? – Paradoxian