众所周知,TextView可以用来显示文字。但它的功能还不止如此,它还可以用来显示链接。这些链接可以是网址,电话等链接,也可以是自己定义的链接。下面介绍添加链接的一些方法。
方法一:使用TextView的autolink属性,它的取值可以是以下几种:
具体意义可以看上图,all是它前面所用属性的或。
用法如下:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text1" android:layout_width="match_parent"
android:layout_height="match_parent" android:autoLink="all"
android:text="http://baidu.com" />
方法二:
用一个字符串资源来加入链接:
<string name="link_text_manual"><b>text2:</b> This is some other
text, with 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设置字符串:
TextView t = findViewById(R.id.TextView01);
t.setText(R.string.link_text_manual);
t.setMovementMethod(LinkMovementMethod.getInstance());
方法三:
在java 代码中使用Html
TextView t = (TextView) findViewById(R.id.TextView01);
t.setText(Html.fromHtml("<b>text3:</b> Text with a "
+ "<a href="http://www.google.com">link</a> "
+ "created in the Java source code using HTML."));
t.setMovementMethod(LinkMovementMethod.getInstance());
方法四:
使用SpannableString
SpannableString s = new SpannableString("text4: Click here to dial the phone.");
s.setSpan(new StyleSpan(Typeface.BOLD), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(newURLSpan("tel:41555512"),13,17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView t = (TextView) findViewById(R.id.TextView01);
t.setText(s);
t.setMovementMethod(LinkMovementMethod.getInstance());
设置个别文字格式
- import android.app.Activity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.text.Html;
- import android.text.Spannable;
- import android.text.style.BackgroundColorSpan;
- import android.text.style.StyleSpan;
- import android.widget.EditText;
- import android.widget.TextView;
- public class AndroidFronColorTest extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TextView htmlFormateTextView = (TextView)findViewById(R.id.testTextView);
- String source = "这只是一个测试,测试<u>下划线</u>、<i>斜体字</i>、<font color='red'>红色字</font>的格式";
- htmlFormateTextView.setText(Html.fromHtml(source));
- EditText et = (EditText) findViewById(R.id.textView);
- Spannable sp = (Spannable) et.getText();
- sp.setSpan(new BackgroundColorSpan(Color.RED), 0, 5,
- Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 6, 11,
- Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- }