andorid TextView中显示html元素控件

个人学习记录:

android  TextView显示html元素控件:

activity代码如下:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_textview);
        textview1 = (TextView) findViewById(R.id.textview1);
        textview2 = (TextView) findViewById(R.id.textview2);
        String html = "<font color='red'>I love android</font><br>";
        html += "<font color='#0000ff'><big><i>I love android</i></big></font><p>";
        html += "<big><a href='http://www.baidu.com'>百度</a></big>";
        
        //使用Html.fromHtml()将标签字符串转换成CharSequence对像
        CharSequence charSequence = Html.fromHtml(html);
        textview1.setText(charSequence);
        //设置点击的时候产生超链接
        textview1.setMovementMethod(LinkMovementMethod.getInstance());
        String text = "我的URL:http:www.sina.com\n";
        text += "我的Email:littleheping@163.com\n";
        text += "我的电话:13651083254";
        //在textview2中增加属性android:autoLink="all"来产生超链接效果。
        textview2.setText(text);
        textview2.setMovementMethod(LinkMovementMethod.getInstance());
    }

layout中布局文件代码如下:test_textview.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">
    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20sp"
       />
    <TextView 
        android:id='@+id/textview2'
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20sp"
        android:autoLink="all"
        android:textSize="20sp"
        android:text="@string/link_text"
        />

</LinearLayout>

其中:textview2中增加了autoLink属性为all表示将文本转换为超链接:

各属性如图:

原文地址:https://www.cnblogs.com/wuheping/p/2782247.html