要在Android TextView中实现HTML文本在行尾换行,可以使用以下代码示例:
TextView textView = findViewById(R.id.textView);
String htmlText = "This is a long line of text that needs to be wrapped at the end of the line. This is a long line of text that needs to be wrapped at the end of the line. This is a long line of text that needs to be wrapped at the end of the line.";
textView.setText(Html.fromHtml(htmlText));
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import org.xml.sax.XMLReader;
public class HtmlTagHandler implements Html.TagHandler {
private static final String TAG_BR = "br";
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equalsIgnoreCase(TAG_BR) && !opening) {
output.append("\n");
}
}
}
TextView textView = findViewById(R.id.textView);
String htmlText = "This is a long line of text that needs to be wrapped at the end of the line. This is a long line of text that needs to be wrapped at the end of the line. This is a long line of text that needs to be wrapped at the end of the line.";
// 设置自定义的HtmlTagHandler
HtmlTagHandler htmlTagHandler = new HtmlTagHandler();
textView.setText(Html.fromHtml(htmlText, null, htmlTagHandler));
通过这个解决方法,HTML文本将在TextView中的行尾处自动换行。