Android中的Linkify可以用来判断一个字符串是电话号码、Email、网址或是其他。下面就一个例子来说明它的用法。当字符串在TextView中显示时,点击该字符串手机就会调用Intent,自动对该字符串进行判断,如果是网址就会自动启动浏览器打开该网页;如果是电话号码就会自动打开拨号器进行打电话······
程序如下所示:
import android.app.Activity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class A02Activity extends Activity {
private TextView tv;
private EditText et;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.tv);
et=(EditText)findViewById(R.id.et);
et.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
tv.setText(et.getText());
Linkify.addLinks(tv, Linkify.PHONE_NUMBERS|Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES);
return false;
}
});
}
}
res/layout/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:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText
android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
也可以不在程序中用Linkify,而在res/layout/main.xml中使用android:autoLink="all"(这个适合所有的android手机支持的标识)或者是android:autoLink="web|phone|email"(这个支持指定的android手机支持的标识),具体举例如下:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class A03Activity extends Activity {
TextView tv01,tv02,tv03;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv01=(TextView)findViewById(R.id.tv01);
tv02=(TextView)findViewById(R.id.tv02);
tv03=(TextView)findViewById(R.id.tv03);
tv01.setText("www.baidu.com");
tv02.setText("18775828658");
tv03.setText("1650967185@qq.com");
}
}
res/layout/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:id="@+id/tv01"
android:autoLink="all"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/tv02"
android:autoLink="all"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv03"
android:autoLink="all"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>