作者:吴佑霖雅旺 | 来源:互联网 | 2023-01-19 21:47
本例主要研究一下如何在TextView中显示网页链接和改变特定文字颜色1.main.xml<LinearLayoutxmlns:androidhttp:schemas
本例主要研究一下如何在TextView中显示网页链接和改变特定文字颜色
1.main.xml
2.MainActivity.java:
package com.yayun.edittextdatedemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView1;
private TextView mTextView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView1=(TextView) findViewById(R.id.tv_url);
mTextView2=(TextView) findViewById(R.id.tv_color);
String text="Visit 百度网";
mTextView1.setText(Html.fromHtml(text));//以链接的形式显示
mTextView1.setMovementMethod(LinkMovementMethod.getInstance());//在单击链接时凡是要执行的动作,都必须设置MovementMethod对象
Spannable sTextSpannable=new SpannableString(mTextView2.getText());
sTextSpannable.setSpan(new BackgroundColorSpan(Color.RED),1,4,0);//spannableString.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
sTextSpannable.setSpan(new ForegroundColorSpan(Color.BLUE),5,9,0);
mTextView2.setText(sTextSpannable);
}
}
3.运行实例:
![](https://img1.php1.cn/3cd4a/24ed6/978/771e0555fe2a4e43.jpeg)
总结
1.Html.fromHtml(text),将文本转成html形式;
2.mTextView1.setMovementMethod(LinkMovementMethod.getInstance());//在单击链接时凡是要执行的动作,都必须设置MovementMethod对象
3.sTextSpannable.setSpan(new BackgroundColorSpan(Color.RED),1,4,0);//spannableString.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);