Andoid自動判斷輸入是電話,網址或者Email的方法—-Linkify的應用!

來源:互聯網
上載者:User

本節要講的是,當我們在一個EditText輸入電話或者網址還是Email的時候,讓Android自動判斷,當我們輸入的是電話,我們點擊輸入內容將調用打電話程式,當我們輸入是網址點擊將開啟瀏覽器程式.而Linkify很好的解決了這個問題.我們將分四步來完成這個Demo.

 

Step 1:建立一個Android工程,命名為LinkifyDemo.

 

Step 2:開啟main.xml檔案,將其內容修改為如下內容:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="請輸入電話或者E-mail或者網址:"
    />
<EditText
 android:id="@+id/et1"
 android:layout_width="340px"
 android:layout_height="wrap_content"
/>

<TextView
 android:id="@+id/tv1"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
/>

</LinearLayout>

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:運行之.將出現如下效果:

 

  

 

以輸入為電話為例,也就是右上方這張圖片,當我們點擊這個號碼時候,系統將自動調用打電話的應用程式,如:

 

 

擴充學習:

 

當然我們還有更簡單的方法.就是在main.xmlidtvTextView裡申明這句話也就是:

 

<TextView
 android:id="@+id/tv1"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"

 android:autoLink="web|phone|email"
/>

也能達到同樣的效果,呵呵.今天到此結束,謝謝大家!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.