Android Material Design Floating Label for EditText Tutorial
One of the basic UI widgets in Android is an EditText. It is generally used to take inputs from the user. While typing in EditText , it hides the hint which may create problem to identify EditText without label but last year when material design was released, a new concept of floating labels was introduced. This new Android floating label EditText concept initially showed a label as a hint; when user enters a value in the EditText, that hint moves on to the top of the EditText as a floating label. The question is here now : how to implement the new Android floating action EditText. Answer to this, use the new Android TextInputLayout around the EditText.
What is TextInputLayout ?
A TextInputLayout widget behaves exactly as a LinearLayout does, it’s just a wrapper. TextInputLayout only accepts one child element, similar to a ScrollView. The child element needs to be an EditText element . When TextInputLayout is used around an EditText is automatically takes the hint text defined in the EditText and shows it as a floating label. Another feature we can also set an error message to EditText by using setErrorEnabled() and setError() methods .
TextInputLayout takes the value of android:hint assigned to EditText and displays it as floating label.
Let’s Get it Working
In this tutorial we are going to learn how to how to float label on EditText. To really understand the usage of TextInputLayout we will create an app . The App contains simple registration form with floating label, form validations and error messages.
Step 1 ) Update build.gradle file
Before you can use TextInputLayout in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project .
dependencies { ... compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' }
Step 2) Update strings.xml .
Add the below string values to the string.xml located in res => values => strings.xml .
<resources> <string name="app_name">Floating Labels</string> <string name="hint_full_name">Full Name</string> <string name="hint_email">Email</string> <string name="hint_age">Age</string> <string name="hint_password">Password</string> <string name="text_sign_up">SIGN UP</string> <string name="error_message_name">Enter Full Name</string> <string name="error_message_email">Enter Valid Email</string> <string name="error_message_age">Enter Age</string> <string name="error_message_password">Enter Password</string> <string name="success_message">Sign Up Successful</string> </resources>
Step 3) Update dimens.xml .
Add the below dimensions to the dimens.xml located in res => values => dimens.xml .
<resources> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="button_margin_top">50dp</dimen> </resources>
Step 4) Update activity_main.xml .
Open the layout file for the MainActivity.java i.e activity_main.xml and add the below code in you layout file . The code will create a simple registration form containing 4 input fields Full Name , Email , Age and Password with Sign Up Button .
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.androidtutorialshub.floatinglabels.MainActivity"> <android.support.design.widget.TextInputLayout android:id="@+id/text_input_layout_name" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit_text_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_full_name" android:inputType="text" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/text_input_layout_email" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit_text_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_email" android:inputType="textEmailAddress" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/text_input_layout_age" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit_text_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_age" android:inputType="number" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/text_input_layout_password" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit_text_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/hint_password" android:inputType="textPassword" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/button_sign_up" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/button_margin_top" android:background="@color/colorPrimary" android:text="@string/text_sign_up" android:textColor="@android:color/white" /> </LinearLayout>
Step 5) Write Validation Helper Class.
Create a class named ValidationHelper.java and add below code in it . The code will create validation methods for input field . Validation to check empty input and valid email .
package com.androidtutorialshub.floatinglabels; import android.app.Activity; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class ValidationHelper { private Context context; /** * constructor * @param context */ public ValidationHelper(Context context) { this.context = context; } /** * method to check EditText filled . * @param editText * @param textInputLayout * @param message * @return */ public Boolean isEditTextFilled(EditText editText, TextInputLayout textInputLayout, String message) { String value = editText.getText().toString().trim(); if (value.isEmpty()) { textInputLayout.setError(message); hideKeyboardFrom(editText); return false; } else { textInputLayout.setErrorEnabled(false); } return true; } /** * method to check valid email inEditText . * @param editText * @param textInputLayout * @param message * @return */ public Boolean isEditTextEmail(EditText editText, TextInputLayout textInputLayout, String message) { String value = editText.getText().toString().trim(); if (value.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(value).matches()) { textInputLayout.setError(message); hideKeyboardFrom(editText); return false; } else { textInputLayout.setErrorEnabled(false); } return true; } /** * method to Hide keyboard * @param view */ private void hideKeyboardFrom(View view) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } }
Step 6) Update Main Activity Class.
Now Open MainActivity.java and make some changes in code . Here i added the methods to validate the input fields Full Name,Email,Age and Password using the ValidationHelper class which i described above .
package com.androidtutorialshub.floatinglabels; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //TextInputLayout variables private TextInputLayout textInputLayoutName; private TextInputLayout textInputLayoutEmail; private TextInputLayout textInputLayoutAge; private TextInputLayout textInputLayoutPassword; //EditText variables private EditText editTextName; private EditText editTextEmail; private EditText editTextAge; private EditText editTextPassword; //Button private Button buttonSignUp; private ValidationHelper validation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); initListeners(); } /** * method to initialize views objects */ private void initViews() { textInputLayoutName = (TextInputLayout) findViewById(R.id.text_input_layout_name); textInputLayoutEmail = (TextInputLayout) findViewById(R.id.text_input_layout_email); textInputLayoutAge = (TextInputLayout) findViewById(R.id.text_input_layout_age); textInputLayoutPassword = (TextInputLayout) findViewById(R.id.text_input_layout_password); editTextName = (EditText) findViewById(R.id.edit_text_name); editTextEmail = (EditText) findViewById(R.id.edit_text_email); editTextAge = (EditText) findViewById(R.id.edit_text_age); editTextPassword = (EditText) findViewById(R.id.edit_text_password); buttonSignUp = (Button) findViewById(R.id.button_sign_up); validation = new ValidationHelper(this); } /** * method to initialize listeners */ private void initListeners() { buttonSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkValidation(); } }); } /** * method for validation of form on sign up button click */ private void checkValidation() { if (!validation.isEditTextFilled(editTextName, textInputLayoutName, getString(R.string.error_message_name))) { return; } if (!validation.isEditTextEmail(editTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) { return; } if (!validation.isEditTextFilled(editTextAge, textInputLayoutAge, getString(R.string.error_message_age))) { return; } if (!validation.isEditTextFilled(editTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))) { return; } Toast.makeText(getApplicationContext(),getString(R.string.success_message),Toast.LENGTH_LONG).show(); } }
This whole sample would result a screen like this: