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

2018-01-26  本文已影响0人  温兴婷

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>

重要的事情说三遍

上一篇 下一篇

猜你喜欢

热点阅读