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中的行尾处自动换行。

相关内容

热门资讯

一分钟教你!山西扣点子辅助器,... 一分钟教你!山西扣点子辅助器,决战卡五星辅助,细节开挂辅助教程(存在有挂);无需打开直接搜索加薇13...
科技介绍!小逸碰胡脚本,情怀打... 科技介绍!小逸碰胡脚本,情怀打七开辅助,分享开挂辅助教程(有挂方式);无需打开直接搜索打开薇:136...
记者发布!爱来辅助器,杭州都莱... 记者发布!爱来辅助器,杭州都莱破解版,盘点开挂辅助教程(有挂头条);无需打开直接搜索打开薇:1367...
玩家必备科普!钱塘十水三挂件,... 玩家必备科普!钱塘十水三挂件,开心泉州小程序有挂吗,细节开挂辅助教程(新版有挂);无需打开直接搜索薇...
玩家必用!蜀山四川小程序辅助,... 玩家必用!蜀山四川小程序辅助,掌电竞技辅助工具,细节开挂辅助教程(有挂方略);无需打开直接搜索薇:1...
今日科普!闲玩暗宝辅助软件,浙... 今日科普!闲玩暗宝辅助软件,浙江游戏大厅脚本修改,正品开挂辅助教程(有挂方略);无需打开直接搜索加(...
终于知道!小唐家乐园山西辅助软... 终于知道!小唐家乐园山西辅助软件,广西友乐辅助器,关于开挂辅助教程(有挂功能);无需打开直接搜索加薇...
详细说明!福建微乐小程序修改器... 详细说明!福建微乐小程序修改器,小闲川南宜宾辅助,必看开挂辅助教程(竟然有挂);无需打开直接搜索薇:...
关于!微信大a辅助,黑桃a3辅... 关于!微信大a辅助,黑桃a3辅助,正版开挂辅助教程(存在有挂);无需打开直接搜索加(薇:136704...
我来教教大家!蜀渝牌乐汇修改器... 我来教教大家!蜀渝牌乐汇修改器,河洛杠次脚本开发,曝光开挂辅助教程(有挂工具);无需打开直接搜索加薇...