Make a registration form in Android
We make a simple layout to display all the components we need for registration. We explain how to make the layout in the Layout Editor. Read our blog post about Android Studio Layout Editor if you want to learn more about Android Layout Editor.
1. First, we create a new project and add an empty activity.
2. We use ConstraintLayout for this sample, check for all the constraints after you finish, a picture of our layout with constraints is below (after the last step).
3. Add the first EditText for the first name.
- Name it "firstName" (use the id attribute to name the component).
- Set text to "".
- Set hint to "First name".
- This one should have 3 constraints; one links to the top of the screen, second to left border and third to the right border.
4. Add EditText for the last name.
- Name it "lastName".
- Set text to "".
- Set hint to "First name".
- This one should have 3 constraints; one linked to the bottom of "First name", second to left border and third to the right border.
5. Add EditText for postal address.
- Name it "address".
- Set text to "".
- Set hint to "Postal address".
- This one should have 3 constraints; one linked to the bottom of "Last name", second to left border and third to the right border.
6. Add EditText for email.
- Name it "email".
- Set text to "".
- Set hint to "Email".
- This one should have 3 constraints; one linked to the bottom of "Postal address", second to left border and third to the right border.
7.Add a Button for registration.
- Name it "registration".
- Set text to "Registration".
8. Your final layout should now look something like this:
Linking components from layout to the code
Linking layout and code (activity_main.xml and MainActivity.java) is one of the main tasks in programming an application. This is the way we tell the code where the components. Once we link the variables with components, we can change the attributes and read the values that user entered.
9. Let's go to the MainAcitvity.java
10. Declare all the variables we need for our elements on the screen, put these variables at the beginning of the MainActivity class, just after the declaration (of the class).
11. Next, we need to find all the controls and set value to variables in our activity. In fact, we do this in the onCreate method just after the line "setContentView(R.layout.activity_main);"
How to check if data is valid for registration form in Android
Now we have all the code we need to start writing the validation functionality. We have variables for all the components, and we can check the values the user enters. We do this in a central validation function, called checkDataEntered, but first, we need a listener for the click on the register button.
12. Add a new onClickListener to our button after the code that finds elements on our activity.