最近看到一篇文章,讲了TextView的属性,今天我就讲讲它的autoLink属性
首先看效果图:
这种链接方式是如何实现的呢?
1.布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mag.administrator.textviewdemo.MainActivity">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"
android:text="@string/text_one" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text1"
android:autoLink="all" />
</RelativeLayout>
其中@string/text_one 所引用的
<string name="text_one">
<b>text_auto_linkify: Various kinds
of data that will be auto-linked.</b>
In this text are some things that are actionable. For instance,
you can click on http://www.google.com and it will launch the
web browser. You can click on google.com too. If you
click on (415) 555-1212 it should dial the phone. Or just write
foobar@example.com for an e-mail link. If you have a URI like
http://www.example.com/lala/foobar@example.com you should get the
full link not the e-mail address. Or you can put a location
like 1600 Amphitheatre Parkway, Mountain View, CA 94043. To summarize:
https://www.google.com, or 650-253-0000, somebody@example.com,
or 9606 North MoPac Expressway, Suite 400, Austin, TX 78759.
</string>
2.java代码中
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SpannableString ss = new SpannableString(
"text_spannable: Manually created spans. Click here to dial the phone:4155551212");
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 39,
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
TextView textViewSpan = (TextView) findViewById(R.id.text2);
textViewSpan.setText(ss);
textViewSpan.setMovementMethod(LinkMovementMethod.getInstance());
}
}
好了,分析下:布局文件中是设置了两段文字的,第一个TextView的实现方式就是使用了autoLink属性,然后在string.xml文件中写上所引用字符串就行了。 < b > 在html代码中是加粗的标签
第二个TextView也使用了autoLink属性,但是没有设置text,而是在Java代码中设置的,这样的使用场景可以是在动态加载,从网络中加载数据。