|
6 | 6 | import android.text.method.ScrollingMovementMethod; |
7 | 7 | import android.widget.TextView; |
8 | 8 |
|
| 9 | +import androidx.core.text.HtmlCompat; |
| 10 | + |
9 | 11 | public class FormatViewUtils { |
10 | 12 | private static int MAXIMUM_ROW = 300; |
11 | 13 | private static int MAXIMUM_LENGTH = 10000; |
@@ -36,24 +38,39 @@ public static void scrollBackToTop(TextView textView) { |
36 | 38 | /** |
37 | 39 | * show data to Activity |
38 | 40 | * |
39 | | - * @param htmlStr Support html tags |
| 41 | + * @param str Support html tags |
40 | 42 | * @param pattern time format yyyyMMddHHmmss or .... |
41 | 43 | */ |
42 | | - public static void formatData(TextView tv, String htmlStr, String pattern) { |
43 | | - if (tv != null && !ObjectUtils.isEmpty (htmlStr)) { |
| 44 | + public static void formatData(TextView tv, String str, String pattern) { |
| 45 | + // 假设 ObjectUtils.isEmpty 和 TimeUtils.getTodayDateHms 已经定义 |
| 46 | + if (tv != null && !ObjectUtils.isEmpty(str)) { |
| 47 | + |
| 48 | + // --- 换行处理的核心修改 --- |
| 49 | + // 1. 将字符串中的普通换行符 '\n' 替换为 HTML 换行标签 "<br>"。 |
| 50 | + String htmlStr = str.replace("\n", "<br>"); |
| 51 | + // ------------------------ |
| 52 | + |
44 | 53 | // 如果行数大于 MAXIMUM_ROW ,清空内容 |
45 | 54 | CharSequence currentText = tv.getText(); |
46 | | - if (currentText.length() > MAXIMUM_LENGTH||tv.getLineCount()>MAXIMUM_ROW) { |
47 | | - tv.setText (""); |
| 55 | + if (currentText.length() > MAXIMUM_LENGTH || tv.getLineCount() > MAXIMUM_ROW) { |
| 56 | + tv.setText(""); |
48 | 57 | } |
49 | | - boolean isNull = ObjectUtils.isEmpty (pattern); |
50 | | - tv.append (isNull ? "" : TimeUtils.getTodayDateHms (pattern) + ":"); |
51 | | - tv.append (Html.fromHtml (htmlStr)); |
52 | | - tv.append ("\n"); |
53 | | - Layout layout = tv.getLayout ( ); |
| 58 | + |
| 59 | + boolean isNull = ObjectUtils.isEmpty(pattern); |
| 60 | + tv.append(isNull ? "" : TimeUtils.getTodayDateHms(pattern) + ":"); |
| 61 | + |
| 62 | + // 2. 使用 Html.fromHtml() 处理替换后的 HTML 字符串 |
| 63 | + // 推荐使用兼容性更好的 HtmlCompat |
| 64 | + tv.append(HtmlCompat.fromHtml(htmlStr, HtmlCompat.FROM_HTML_MODE_LEGACY)); |
| 65 | + |
| 66 | + // 3. 在日志条目末尾追加的换行符 (保持不变) |
| 67 | + tv.append("\n"); |
| 68 | + |
| 69 | + // 滚动逻辑 (保持不变) |
| 70 | + Layout layout = tv.getLayout(); |
54 | 71 | if (layout != null) { |
55 | | - int scrollAmount = layout.getLineTop (tv.getLineCount ( )) - tv.getHeight ( ); |
56 | | - tv.scrollTo (0, scrollAmount > 0 ? scrollAmount : 0); |
| 72 | + int scrollAmount = layout.getLineTop(tv.getLineCount()) - tv.getHeight(); |
| 73 | + tv.scrollTo(0, scrollAmount > 0 ? scrollAmount : 0); |
57 | 74 | } |
58 | 75 | } |
59 | 76 | } |
|
0 commit comments