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

相关内容

热门资讯

wepoke透明挂要多少钱!w... wepoke透明挂要多少钱!wepoke透视挂靠谱,(we poker)其实是有挂,新2025教程(...
德扑之星安卓模拟器!德扑之星软... 德扑之星安卓模拟器!德扑之星软件铺牌器,(德扑之星)真是有挂,解说技巧(黑科技工具);1、玩家可以在...
aapoker外挂!aa扑克有... aapoker外挂!aa扑克有外挂吗,(aapokEr)总是是有挂,新2025教程(黑科技黑科技)亲...
wepokeai代打技巧!We... wepokeai代打技巧!WePoKe透明挂,(wEPoke)果然有挂,黑科技教程(黑科技助手);1...
微扑克辅助工具!微扑克ai算牌... 微扑克辅助工具!微扑克ai算牌器,(微扑克)切实真的是有挂,透视教程(黑科技透明挂)1、上手简单,内...
wpk辅助器小程序!wpk到底... wpk辅助器小程序!wpk到底有没有外挂,(wPk)果然有挂,AA德州教程(黑科技辅助器)wpk到底...
wpk辅助软件叫什么!wpk黑... wpk辅助软件叫什么!wpk黑科技软件可信吗,(WpK)总是有挂,新2025版(黑科技功能);1.w...
wpk辅助器是真是假!wpk透... wpk辅助器是真是假!wpk透明挂,(WpK)确实是有挂,力荐教程(黑科技科技);1、wpk辅助器是...
wepoke辅助软件靠谱吗!w... wepoke辅助软件靠谱吗!wepoke有挂么,(WepoKe)都是存在有挂,介绍教程(黑科技辅助挂...
wepoke黑科技!we-po... wepoke黑科技!we-poker辅助软件演示,(WepoKe)果然真的是有挂,揭秘攻略(黑科技辅...