InputTextLayout is used to wrap an EditText and to show hint in floating label when user types in the EditText . It makes the form fields very stylish. We can also set & get errors when validating the input data. InputTextLayout is part of Design Support library.
InputTextLayout inherits constants from LinearLayout, ViewGroup and View.
To use InputTextLayout:
Example: Display Login Form using TextInputLayout with validation
Step 1: we need to add a library in build.gradle file in Android Studio:
1 |
compile 'com.android.support:design:22.2.1' |
Step 2: Create an xml file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/email_layout"> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:hint="Email" android:inputType="textEmailAddress"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/password_layout"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:hint="Password" android:inputType="textPassword"/> </android.support.design.widget.TextInputLayout> |
In above code we have wraped Edit Text into a TextInputLayout.
When user clicks on EditText area, hint floats up. User can see following UI
Step 3: Write code in java file.
1 2 3 4 5 |
TextInputLayout inputLayoutEmail = (TextInputLayout) findViewById(R.id.email_layout); EditText inputEmail = (EditText) findViewById(R.id.email); TextInputLayout inputLayoutPassword = (TextInputLayout) findViewById(R.id.password_layout); EditText inputPassword = (EditText) findViewById(R.id.password); |
Now, setError & setErrorEnable on TextInputLayout when validating the user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Checking for EditText is empty or not String emailId = inputEmail.getText().toString().trim(); if(emailId.isEmpty()) inputLayoutEmail.setError("Email is required!"); else inputLayoutPassword.setErrorEnabled(false); //Checking for password length String password = inputPassword.getText().toString().trim(); if(password.length()<8) inputLayoutPassword.setError("Enter minimum 8 characters"); else inputLayoutPassword.setErrorEnabled(false); |
In above code, We are setting error on instance of TextInputLayout. If email address is empty or password length is less than 8 then it will show an error.