---
title: "Andoid自动判断输入是电话,网址或者Email的方法----Linkify的应用!"
author: "mmdev"
date: "2009-12-13T22:34:00Z"
tags: []
slug: "andoid-email-linkify"
draft: false
lastmod: "2009-12-13T22:34:00Z"
id: 990402
url: "https://mmdev.iteye.com/blog/990402"
---

本节要讲的是,当我们在一个**EditText**输入电话或者网址还是**Email**的时候,让**Android**自动判断,当我们输入的是电话,我们点击输入内容将调用打电话程序,当我们输入是网址点击将打开浏览器程序.而**Linkify**很好的解决了这个问题.我们将分四步来完成这个**Demo**.

**Step 1**:新建一个**Android**工程,命名为**LinkifyDemo**.

**Step 2:**打开**main.xml**文件,将其内容修改为如下内容:

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
android:orientation="vertical"  
android:layout\_width="fill\_parent"  
android:layout\_height="fill\_parent"  
&gt;  
&lt;TextView  
android:layout\_width="fill\_parent"  
android:layout\_height="wrap\_content"  
**android:text="请输入电话或者E-mail或者网址:"**  
/&gt;  
**&lt;EditText**  
**android:id="@+id/et1"**  
**android:layout\_width="340px"**  
**android:layout\_height="wrap\_content"**  
**/&gt;**  
**&lt;TextView**  
**android:id="@+id/tv1"**  
**android:layout\_width="fill\_parent"**  
**android:layout\_height="wrap\_content"**  
**/&gt;**  
&lt;/LinearLayout&gt;

**Step 3:**在主应用程序**LinkifyDemo**.**java**里代码修改如下:

package com.android.test;

import android.app.Activity;  
import android.os.Bundle;  
**import android.text.util.Linkify;**  
**import android.view.KeyEvent;**  
**import android.view.View;**  
**import android.widget.EditText;**  
**import android.widget.TextView;**

public class LinkifyDemo extends Activity {

private EditText et;  
private TextView tv;  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.main);

**//获取资源**  
**et = (EditText)findViewById(R.id.et1);**  
**tv = (TextView)findViewById(R.id.tv1);**  
**//增加事件响应**  
**et.setOnKeyListener(new EditText.OnKeyListener()**{  
@Override  
public boolean onKey(View v, int keyCode, KeyEvent event) {  
**tv.setText(et.getText());**  
**//判断输入的类型是哪种,并与系统连接**  
**Linkify.addLinks(tv, Linkify.WEB\_URLS|**  
**Linkify.EMAIL\_ADDRESSES|Linkify.PHONE\_NUMBERS);**

return false;  
}  
});  
}  
}

**Step 4:**运行之.将出现如下效果:

![](http://p.blog.csdn.net/images/p_blog_csdn_net/Android_Tutor/EntryImages/20091213/lf1.jpg)![](http://p.blog.csdn.net/images/p_blog_csdn_net/Android_Tutor/EntryImages/20091213/lf2.jpg)

以输入为电话为例,也就是右上角这张图片,当我们点击这个号码时候,系统将自动调用打电话的应用程序,如下图:

![](http://p.blog.csdn.net/images/p_blog_csdn_net/Android_Tutor/EntryImages/20091213/lf3.jpg)

扩展学习:

当然我们还有更简单的方法.就是在**main.xml**里**id**为**tv**的**TextView**里申明这句话也就是:

**&lt;TextView**  
android:id="@+id/tv1"  
android:layout\_width="fill\_parent"  
android:layout\_height="wrap\_content"

**android:autoLink="web|phone|email"**  
**/&gt;**

也能达到同样的效果,呵呵.今天到此结束,谢谢大家!