Android Studio中如何结合Toast、Intent与OnClickListener实现注册功能
Hey there! Let's build this registration form together, covering all the requirements you mentioned—including the spinner-style DatePicker, age validation, Toast feedback, and Intent navigation to the thank-you page. I'll break it down step by step using Kotlin (with Java notes where relevant too).
We'll use a vertical LinearLayout to arrange all input fields. For the DatePicker, we'll set its mode to spinner to match your requirement:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gap="16dp"> <!-- Username Input --> <EditText android:id="@+id/etUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Username" android:inputType="textPersonName"/> <!-- Full Name Input --> <EditText android:id="@+id/etFullName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Full Name" android:inputType="textPersonName"/> <!-- Email Input --> <EditText android:id="@+id/etEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:inputType="textEmailAddress"/> <!-- Spinner-style DatePicker for Date of Birth --> <DatePicker android:id="@+id/dobPicker" android:layout_width="match_parent" android:layout_height="wrap_content" android:datePickerMode="spinner" android:calendarViewShown="false"/> <!-- Submit Button --> <Button android:id="@+id/btnSubmit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit"/> </LinearLayout>
We'll set up the OnClickListener for the Submit button, handle input validation, check the user's age, and trigger navigation or Toast feedback accordingly:
import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.DatePicker import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.time.LocalDate import java.time.Period class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Get references to all UI elements val etUsername = findViewById<EditText>(R.id.etUsername) val etFullName = findViewById<EditText>(R.id.etFullName) val etEmail = findViewById<EditText>(R.id.etEmail) val dobPicker = findViewById<DatePicker>(R.id.dobPicker) val btnSubmit = findViewById<Button>(R.id.btnSubmit) // Attach click listener to Submit button btnSubmit.setOnClickListener { // Extract input values and trim whitespace val username = etUsername.text.toString().trim() val fullName = etFullName.text.toString().trim() val email = etEmail.text.toString().trim() // First, check if all required fields are filled if (username.isEmpty() || fullName.isEmpty() || email.isEmpty()) { Toast.makeText(this, "Please fill all required fields", Toast.LENGTH_SHORT).show() return@setOnClickListener } // Get selected date from DatePicker (note: month is 0-based) val selectedYear = dobPicker.year val selectedMonth = dobPicker.month + 1 // Convert to 1-based for LocalDate val selectedDay = dobPicker.dayOfMonth // Calculate user's age using LocalDate (API 26+, use ThreeTenABP for older versions) val dateOfBirth = LocalDate.of(selectedYear, selectedMonth, selectedDay) val currentDate = LocalDate.now() val userAge = Period.between(dateOfBirth, currentDate).years // Age validation check if (userAge < 18) { Toast.makeText(this, "You must be at least 18 years old to register", Toast.LENGTH_LONG).show() } else { // Navigate to ThankYouActivity and pass username as extra val intent = Intent(this, ThankYouActivity::class.java) intent.putExtra("USERNAME_EXTRA", username) startActivity(intent) // Optional: Clear input fields after successful submission etUsername.text.clear() etFullName.text.clear() etEmail.text.clear() } } } }
Java Version Age Calculation Note:
If you're using Java, replace the age calculation with this code to handle older Android versions:
Calendar dobCalendar = Calendar.getInstance(); dobCalendar.set(selectedYear, selectedMonth, selectedDay); Calendar currentCalendar = Calendar.getInstance(); int userAge = currentCalendar.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR); // Adjust age if the user hasn't had their birthday yet this year if (currentCalendar.get(Calendar.DAY_OF_YEAR) < dobCalendar.get(Calendar.DAY_OF_YEAR)) { userAge--; }
First, make a new layout activity_thank_you.xml for the confirmation page:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/tvThankYouMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:text="Thank you for registering!"/> </LinearLayout>
Then, create ThankYouActivity.kt to retrieve the username and display the personalized message:
import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class ThankYouActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_thank_you) val tvThankYou = findViewById<TextView>(R.id.tvThankYouMessage) // Get username from Intent, default to "Guest" if null val username = intent.getStringExtra("USERNAME_EXTRA") ?: "Guest" tvThankYou.text = "Thank you for registering, $username!" } }
Don't forget to add ThankYouActivity to your manifest so the app recognizes it:
<activity android:name=".ThankYouActivity" android:exported="false"/>
Key Concepts Recap:
- Toast: Used to show quick, non-intrusive feedback for empty fields or underage validation.
LENGTH_SHORTandLENGTH_LONGcontrol how long the message stays visible. - OnClickListener: Attached directly to the Submit button to handle all user interaction logic in one place.
- Intent: Used to navigate between activities, with
putExtra()passing the username to personalize the thank-you message. - Spinner DatePicker: The
android:datePickerMode="spinner"attribute switches the DatePicker from a calendar view to dropdown spinners, matching your requirement.
内容的提问来源于stack exchange,提问作者user71311

