给textview加链接(4种方式)
使用android:autoLink属性
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:autoLink="all"
android:paddingBottom="8dp"
android:text="@string/link_text_auto"
android:textAppearance="?android:attr/textAppearanceMedium" />
字符串中的URL与phonenumber等会自动链接到
通过在字符串资源文件中加标记,这样链接就会出现,为了激活链接,需要调用textview的setMovementMethod()方法
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:text="@string/link_text_manual"
android:textAppearance="?android:attr/textAppearanceMedium" />
<string name="link_text_manual"><b>text2: Explicit links using <a> markup.</b>
This has markup for a <a href="http://www.google.com">link</a> specified
via an <a> tag. Use a \"tel:\" URL
to <a href="tel:4155551212">dial a phone number</a>.
</string>
TextView t2 = (TextView) findViewById(R.id.text2);
t2.setMovementMethod(LinkMovementMethod.getInstance());
通过代码添加链接
TextView t3 = (TextView) findViewById(R.id.text3);
t3.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."));
t3.setMovementMethod(LinkMovementMethod.getInstance());
不使用HTML进行编码
SpannableString ss = new SpannableString(
"text4: Manually created spans. Click here to dial the phone.");
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);
TextView t4 = (TextView) findViewById(R.id.text4);
t4.setText(ss);
t4.setMovementMethod(LinkMovementMethod.getInstance());