Android TextView HTML文本在行尾换行
创始人
2024-08-19 00:30:05
0

要在Android TextView中实现HTML文本在行尾换行,可以使用以下代码示例:

  1. 首先,在XML布局文件中定义一个TextView控件:

  1. 在Java代码中,获取并设置HTML文本到TextView:
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));
  1. 创建一个自定义的HtmlTagHandler类来处理HTML标签,并在标签结尾处添加一个换行符:
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");
        }
    }
}
  1. 修改Java代码中的TextView设置,以使用自定义的HtmlTagHandler:
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中的行尾处自动换行。

相关内容

热门资讯

九分钟外挂!游戏大厅浙江脚本辅... 九分钟外挂!游戏大厅浙江脚本辅助,方片十三张脚本,安装教程(有挂方法)-哔哩哔哩1、进入到游戏大厅浙...
8分钟外挂!九九山城万州版辅助... 8分钟外挂!九九山城万州版辅助,指尖四川辅助脚本,解说技巧(存在有挂)-哔哩哔哩1、下载好九九山城万...
6分钟外挂!威信茶馆app插件... 6分钟外挂!威信茶馆app插件,微信中至有辅助吗,教你攻略(有挂功能)-哔哩哔哩1)微信中至有辅助吗...
7分钟外挂!闲逸辅助插件,闲聚... 7分钟外挂!闲逸辅助插件,闲聚辅助器,AI教程(果真有挂)-哔哩哔哩1、该软件可以轻松地帮助玩家将闲...
第2分钟外挂!哈狗智能辅助,衢... 第2分钟外挂!哈狗智能辅助,衢州都莱辅助器是真是假,扑克教程(有挂神器)-哔哩哔哩1、打开软件启动之...
第2分钟外挂!丫丫打锅子辅助,... 第2分钟外挂!丫丫打锅子辅助,贪玩互娱辅助,技巧教程(有挂方式)-哔哩哔哩1、实时丫丫打锅子辅助开挂...
六分钟外挂!温州茶苑手机辅助器... 六分钟外挂!温州茶苑手机辅助器,边锋老友内蒙古辅助,细节揭秘(真的有挂)-哔哩哔哩1、操作简单,无需...
第九分钟外挂!余干510k副5... 第九分钟外挂!余干510k副510k,黑桃a3辅助,必胜教程(有挂方法)-哔哩哔哩1、余干510k副...
第9分钟外挂!闲逸免费app辅... 第9分钟外挂!闲逸免费app辅助,金华佛手在线辅助,专业教程(真是有挂)-哔哩哔哩1、不需要AI权限...
4分钟外挂!阿拉游戏中心辅助,... 4分钟外挂!阿拉游戏中心辅助,同城游辅助软件,扑克教程(有挂助手)-哔哩哔哩1、每一步都需要思考,不...