本例主要研究一下如何在TextView中显示网页链接和改变特定文字颜色
1.main.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/tv_url" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HelloWorld,HomeActivity!"/> </LinearLayout>
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 <a href=\"http://www.baidu.com\">百度网</a>"; 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.运行实例:
总结
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);
时间: 2024-10-05 06:36:27