如何在Android中檢查EditText中的文字是否為郵箱地址?
在進入示例之前,我們應該瞭解測試場景。在登入頁面中,通常我們從EditText中獲取郵箱ID和密碼。從EditText獲取郵箱ID時,我們應該知道它是否為有效格式。
此示例演示如何檢查EditText中的文字是否為郵箱地址。
步驟1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟2 − 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" tools:context=".MainActivity"> <EditText android:id="@+id/email" android:hint="Email id" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/valid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check validation" /> </LinearLayout>
在上面的佈局中,我們添加了EditText和按鈕,使用者應該在EditText中輸入郵箱ID或字串,當用戶點選按鈕時,將檢查EditText中輸入字串的有效性。
步驟3 − 將以下程式碼新增到src/MainActivity.java
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { String emailRegEx; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); emailRegEx = "^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,4}$"; final EditText email = findViewById(R.id.email); Button valid = findViewById(R.id.valid); valid.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Pattern pattern = Pattern.compile(emailRegEx); Matcher matcher = pattern.matcher(email.getText().toString()); if (email.getText().toString().isEmpty()) { Toast.makeText(MainActivity.this, "please enter email id", Toast.LENGTH_LONG).show(); } else if (!matcher.find()) { Toast.makeText(MainActivity.this, "Not an email id", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "email id is valid", Toast.LENGTH_LONG).show(); } } }); } }
在上面的程式碼中,使用模式和匹配器,它將查詢給定的字串是否有效。
步驟4 − 無需更改manifest.xml檔案
讓我們嘗試執行您的應用程式。我假設您已將實際的Android移動裝置連線到您的計算機。要在Android Studio中執行應用程式,請開啟專案的其中一個活動檔案,然後單擊執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 −
在上面的示例中,我們在EditText中沒有任何內容,並點選了按鈕,它顯示警告“請填寫郵箱ID”。
在上面的示例中,我們輸入了錯誤的郵箱ID,它顯示警告“無效郵箱ID”。
在上面的示例中,我們輸入了正確的郵箱ID,它輸出“郵箱ID有效”。
廣告