我尝试TextView像这样设置我的 html 文本
my_text.setText(HtmlCompat.fromHtml("<p>This is the awesome place to gain</p><p><strong>awesomeness </strong>and <em>deliciuosness. </em>very<em> </em><u>nice</u></p>", HtmlCompat.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH))
Run Code Online (Sandbox Code Playgroud)
我尝试设置TextView一个边框,我得到了这样的填充底部。
如何删除它?因为我TextView没有设置任何东西
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/my_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border_black_fill_white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)
您看到的这个额外空间实际上是换行符后面跟着另一个换行符。
当您深入研究 HtmlCompat.fromHtml 内部使用的 Html.fromHtml(...) 实现时,您将遇到以下处理段落标签的方法:
private static void handleP(SpannableStringBuilder text) {
int len = text.length();
if (len >= 1 && text.charAt(len - 1) == '\n') {
if (len >= 2 && text.charAt(len - 2) == '\n') {
return;
}
text.append("\n");
return;
}
if (len != 0) {
text.append("\n\n");
}
}
Run Code Online (Sandbox Code Playgroud)
因此,要处理此问题,只需修剪字符串,以便删除末尾添加的空格。
String html = "<p>This is the awesome place to gain</p><p><strong>awesomeness </strong>and <em>deliciuosness. </em>very<em> </em><u>nice</u></p>"
CharSequence trimmedString = trim(Html.fromHtml(html));
myText.setText(trimmedString);
public static CharSequence trim(CharSequence s) {
int start = 0;
int end = s.length();
while (start < end && Character.isWhitespace(s.charAt(start))) {
start++;
}
while (end > start && Character.isWhitespace(s.charAt(end - 1))) {
end--;
}
return s.subSequence(start, end);
}
Run Code Online (Sandbox Code Playgroud)
这会给你想要的结果。
在kotlin 中,它只是使用trim()方法:
val stringHtml = "<p>This is the awesome place to gain</p><p><strong>awesomeness </strong>and <em>deliciuosness. </em>very<em> </em><u>nice</u></p>"
val spannedHtml = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(stringHtml, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(stringHtml)
}
my_text.text = spannedHtml.trim()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
876 次 |
| 最近记录: |