TextView设置内容下划线加粗等html样式实例及注意事项

TextView设置内容下划线加粗等html样式实例及注意事项

效果图

test01.png

Java代码

package com.myapplication;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv1 = (TextView)findViewById(R.id.tv1);
        TextView tv2 = (TextView)findViewById(R.id.tv2);
        String st = "TextView内的文本:<u>下划线</u> <i>斜体字</i> <font color='#ff0000'>设置字体颜色为红色</font><strong>加粗</strong> ";
        Spanned  result ;
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){//androidN+之后废除了Html.fromHtml(String),用Html.fromHtml(String,flag)代替
            result= Html.fromHtml(st,Html.FROM_HTML_MODE_LEGACY);
        }else {
            result =Html.fromHtml(st);
        }
        //必须直接写result
        tv1.setText(result);
        //如果拼接其他内容则无效,比如:
        tv2.setText("添加其他内容无效"+result);

    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="left"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
   >
    <TextView
        android:textSize="20sp"
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <TextView
        android:layout_marginTop="20dp"
        android:textSize="20sp"
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
</LinearLayout>

重要的事情说三遍

  • 不要再settext中添加其他内容,直接放入Html.fromHtml()方法得到的返回值,不然无效样式无效
  • 不要再settext中添加其他内容,直接放入Html.fromHtml()方法得到的返回值,不然无效样式无效
  • 不要再settext中添加其他内容,直接放入Html.fromHtml()方法得到的返回值,不然无效样式无效
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • #练习 **基本原理:** 将图像空间中的曲线变换到参数空间中,通过检测参数空间中的极值点,确定出该曲线的描述参数...
    haiguangboy阅读 227评论 0 0
  • 1、Spring MVC工作原理 a.客户端请求提交到前端控制器DispatcherServlet b.由Disp...
    175bd0161f3f阅读 210评论 0 0
  • 今天洗头的时候,梳子上黑乎乎的头发刺的我心疼。拿吹风机吹完头发,手一捏,发量少的可怜,枉我平日里那般护理...
    请叫我千花大人阅读 486评论 4 8
  • 一、纳税人 1.国有企业、集体企业、私营企业、联营企业、股份制企业、有生产经营所得和其他所得的其他组织。 2.个人...
    木先生is澜阅读 491评论 0 0
  • 速记、速读、一目十行、过目不忘……快、速成是现代人快餐式、碎片化阅读的兴奋点。打着快和速成噱头的培训班用其一贯的煽...
    裕文书屋阅读 313评论 1 1