android Linkify的用法

来源:互联网 发布:caxa方块线切割编程 编辑:程序博客网 时间:2024/05/06 02:20
之前一直疑惑android上的链接是怎么生成的,今天终于知道了,happy的同时,把这个小东西跟朋友们分享以下。
首先还是延续我一贯的作风,先贴出来布局页面的代码(linkifylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:id="@+id/myTextView1"
android:layout_width= "wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText android:id="@+id/myEditText1"
android:layout_width= "wrap_content"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>

主程序LinkifyTextView.java
package test.shi;

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

public class LinkifyTextView extends Activity {

private TextView myTextView1;
private EditText myEditText1;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.linkifylayout);

myTextView1=(TextView)findViewById(R.id.myTextView1);
myEditText1=(EditText)findViewById(R.id.myEditText1);

myEditText1.setOnKeyListener(new EditText.OnKeyListener()
{

@Override
public boolean onKey(View v, int arg1, KeyEvent arg2) {
  // TODO Auto-generated method stub

myTextView1.setText(myEditText1.getText());

//此处是关键,感应myTextView1是web链接还是email链接,或者是电话号码
Linkify.addLinks
(
myTextView1,Linkify.WEB_URLS|
Linkify.EMAIL_ADDRESSES|
Linkify.PHONE_NUMBERS
);

return false;
}


});
}

}


除了使用Linkify之外,还可以在linkifylayout.xml文件中设置TextView的android:autoLink实现这种HyperLink的效果。如下:

   <TextView android:id="@+id/myTextView1"
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:autoLink="web|email|phone">
</TextView>

通过在程序中设置
myTextView1.setText(“http://www.google.cn”);
myTextView1.setText(“13512345678”);
myTextView1.setText(“hello@126.com”);
这样运行时myTextView1就会生成链接,当用户点击时,会自动调用系统的Intent,以浏览器打开网址、发送邮件或拨打电话。