简体   繁体   English

检测TextView是否换行

[英]Detecting whether or not TextView wraps a line

We are using an ExpandableList of TableViews to display a block of text with line numbers on one side. 我们正在使用TableViews的ExpandableList在一侧显示带有行号的文本块。 First, the string for a given paragraph is set into a text view in the right column of the TableView. 首先,将给定段落的字符串设置为TableView右栏中的文本视图。 Then, a line-number string is generated from the paragraph string and a starting line number. 然后,从段落字符串和起始行号生成行号字符串。 For example, from the string (with a starting line number of 1): 例如,从字符串(起始行号为1)开始:

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.   

the following line number string is generated: 生成以下行号字符串:

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

This string is then placed in the leftmost column of the TableView to show the line number of the string every five lines. 然后,将该字符串放在TableView的最左列中,以每五行显示该字符串的行号。

However, a problem arises when the text size is raised to a point where the lines of text are wrapped (because the line is too big to fit on the screen). 但是,当将文本大小提高到自动换行时,就会出现问题(因为该行太大而无法容纳在屏幕上)。 When this happens, it seems like it is necessary to insert another \\n into the line number string at the site of the text-wrapping, so as to count the potentially multiple lines of wrapped text as a single line. 发生这种情况时,似乎有必要在文本换行的位置的行号字符串中插入另一个\\ n,以便将可能多行换行的文本计为一行。 Is there, therefore, anyway for android to detect whether a line has been wrapped in a TextView, so that the program can know to insert a \\n into the line number string and compensate for line breaks? 因此,无论如何,android是否可以检测到是否在TextView中包裹了一行,以便程序可以知道在行号字符串中插入\\ n并补偿换行符?

First you can compute the on screen width required for the string render. 首先,您可以计算字符串渲染所需的屏幕宽度。 Compare that with your total device/view with to check if you need to insert '\\n' for text wrapping. 将其与设备/视图的总和进行比较,以检查是否需要插入“ \\ n”以进行自动换行。

PS: The code is not tested but should work. PS:该代码未经测试,但应该可以工作。 If you using custom typeface, you can replace Typeface.DEFAULT with your own. 如果使用自定义字体,则可以用自己的字体替换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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM