记录一个可支持 style 属性 HtmlTextView 控件

大家都知道可通过原生API Html.fromHtml(html) 在 TextView 上显示 html 文本,但显示效果有限。

对于复杂效果就不行了,费了点时间找了一些库验证,最终找到一个合适的,在此记录一下。

支持内容挺丰富的,包含很多 html 和 css tag,具体介绍可看 原库项目地址

使用方法

1、build.gradle(项目) repositories 中导入

	maven {
    
     url 'https://dl.bintray.com/sysdata/maven' }
	maven {
    
     url 'http://repo.pageturner-reader.org' }
	mavenCentral()

2、build.gradle(:模块) dependencies 中导入

	//implementation 'it.sysdata.mobile:htmlspanner:1.0.2'
	//因为上面的库拉不下来,所以用 htmlspanner-1.0.3.aar 替代
	implementation files('libs/htmlspanner-1.0.3.aar')
    implementation 'net.sourceforge.htmlcleaner:htmlcleaner:2.16'

htmlspanner-1.0.3.aar下载

3、直接给 textview 设置

		String html = "<p  style=\"font-size:34px;background-color:#FCF8E3;text-align:center\"><font color=\"#BBBDBE\">小池</font></p><p  style=\"font-size:24px;background-color:#D7F6EC;text-align:left\"><font color=\"#333333\">泉眼无声惜细流,树阴照水爱晴柔。小荷才露尖尖角,早有蜻蜓立上头。</font></p>";
		
//        TextView textView = findViewById(R.id.testView);
//        textView.setText(Html.fromHtml(html));

        TextView tv = (TextView) findViewById(R.id.testView);
        int col = tv.getSolidColor();
        HtmlSpanner htmlSpanner = new HtmlSpanner(tv.getCurrentTextColor(), tv.getTextSize());
        htmlSpanner.setBackgroundColor(col);
        tv.setText(htmlSpanner.fromHtml(html));

验证效果

测试 html 文本内容

 <p  style="font-size:34px;background-color:#FCF8E3;text-align:center"><font color="#BBBDBE">小池</font></p><p  style="font-size:24px;background-color:#D7F6EC;text-align:left"><font color="#333333">泉眼无声惜细流,树阴照水爱晴柔。小荷才露尖尖角,早有蜻蜓立上头。</font></p>
 

PC 运行效果图

pCNm7Af.png

Android 运行效果图

pCNeLO1.png

猜你喜欢

转载自blog.csdn.net/u012932409/article/details/132021355