/*
* 这个demon演示了如何将符合预定规划或自定义规则的文本转化为超链接状态
*/
public class MainActivity extends Activity {
private TextView tv1;
private TextView tv2;
private TextView tv3;
private TextView tv4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 通过在tv1的xml文件中为其设置android:autoLink="all"属性
// 使tv1中的文本自动按系统预定规则设置超链接
// 在String.xml中使用<a></a>来标识超链接的文本
tv2 = (TextView) findViewById(R.id.text2);
// 为超链接创建进入接口
tv2.setMovementMethod(LinkMovementMethod.getInstance());
// 通过代码设置超链接的内容
tv3 = (TextView) findViewById(R.id.text3);
tv3.setText(Html
.fromHtml("<b>text3: Constructed from HTML programmatically.</b> Text with a "
+ "<a href=\"http://www.google.com\">link</a> "
+ "created in the Java source code using HTML."));
tv3.setMovementMethod(LinkMovementMethod.getInstance());
//SpannableString定义一个只读字符串,但可以为该字符串的某个部分设置格式
SpannableString ss = new SpannableString(
"text4: Manually created spans. Click here to dial the phone.");
//为第1-30个字符设置加粗
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 30,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new URLSpan("tel:4155551212"), 31 + 6, 31 + 10,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv4 = (TextView) findViewById(R.id.text4);
tv4.setText(ss);
tv4.setMovementMethod(LinkMovementMethod.getInstance());
}
}
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="?android:attr/listDivider"
android:orientation="vertical"
android:showDividers="middle" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text1"
android:autoLink="all"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>