跳转至第二个Activity前验证邮箱地址的实现方案
Got it, let's sort out that email validation problem for you! You want to make sure only valid emails let users jump to the next Activity, right? Here's a straightforward implementation in both Kotlin and Java, which fits your needs perfectly:
First, we'll make a helper method that checks if an email matches a standard valid format using a regex pattern. This function is reusable across your app if you need it elsewhere.
Kotlin Implementation
private fun isValidEmail(email: String): Boolean { // Standard regex pattern for email validation val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$".toRegex() // Trim whitespace to avoid false negatives from accidental spaces return emailRegex.matches(email.trim()) }
Java Implementation
private boolean isValidEmail(String email) { // Standard regex pattern for email validation String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; // Trim whitespace to avoid false negatives from accidental spaces return email.trim().matches(emailRegex); }
Next, hook up this validation to your "next" button's click listener. We'll check the email input first—if it's valid, proceed to the second Activity; if not, show the error Toast.
Kotlin Implementation
// Assume your button has ID btn_next and email input has ID et_email val btnNext = findViewById<Button>(R.id.btn_next) val etEmail = findViewById<EditText>(R.id.et_email) btnNext.setOnClickListener { val inputEmail = etEmail.text.toString() if (isValidEmail(inputEmail)) { // Navigate to the second Activity val intent = Intent(this, SecondActivity::class.java) startActivity(intent) } else { // Show invalid email Toast Toast.makeText(this, "INVALID EMAIL ADDRESS", Toast.LENGTH_SHORT).show() } }
Java Implementation
// Assume your button has ID btn_next and email input has ID et_email Button btnNext = findViewById(R.id.btn_next); EditText etEmail = findViewById(R.id.et_email); btnNext.setOnClickListener(v -> { String inputEmail = etEmail.getText().toString(); if (isValidEmail(inputEmail)) { // Navigate to the second Activity Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); } else { // Show invalid email Toast Toast.makeText(this, "INVALID EMAIL ADDRESS", Toast.LENGTH_SHORT).show(); } });
Quick Note
If you're using View Binding instead of findViewById, just replace the view lookup lines with your binding object (e.g., binding.btnNext and binding.etEmail)—the rest of the logic stays exactly the same.
内容的提问来源于stack exchange,提问作者hatimboubakri

