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("[email protected]");
}
}
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>