用view的XML属性实现超链接

Android 应用的 layout(UI 布局)除了直接改写程序代码的方式外(动态布局),也能使用 XML 文件來做描述(XML-based Layout)。


以下是一个实现超链接(hyperlink)并通过点击自动调用浏览器浏览网页的例子:
用view的XML属性实现超链接_第1张图片
该功能的实现非常简单,我们只需要改写两行XML属性而已。

每一个View都有许多属性,我们可以通过XML来描述每一个View的属性,从而达到控制应用程序的效果。下面以TextView为例,有一个android:autoLink属性可以实现超链接:

android:autoLink

Controls whether links such as urls and email addresses are automatically found and converted to clickable links. The default value is "none", disabling this feature.

Must be one or more (separated by '|') of the following constant values.

Constant Value Description
none 0x00 Match no patterns (default).
web 0x01 Match Web URLs.
email 0x02 Match email addresses.
phone 0x04 Match phone numbers.
map 0x08 Match map addresses.
all 0x0f Match all patterns (equivalent to web|email|phone|map).

This corresponds to the global attribute resource symbol autoLink.


http://code.google.com/intl/zh-TW/android/reference/android/widget/TextView.html#attr_android:autoLink


具体实现:

建立一个android工程,打开main.XML文件,修改如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Young's Blog - http://blog.csdn.net/imyang2007?viewmode=contents"
        android:autoLink="web"
        />


</LinearLayout>


我们给TextView对象新增一个android:autoLink属性,并把属性设动为web,这时只要text属性出现URL,textiew就会自动将URL文本转换成可点击的link。程序执行时,只要点击link,就会自动启用浏览器,并连接该网址,效果如下:
用view的XML属性实现超链接_第2张图片


你可能感兴趣的:(xml,android,浏览器,layout,email,Hyperlink)