Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Implement TextWatcher in Android?

How to Implement TextWatcher in Android?

If there is an application containing a login form to be filled by the user, the login button should be disabled (meaning: it shouldn’t be clickable). When the user enters the credentials of the form the button should be enabled to click for the user. So in this article, we are implementing a TextWatcher to the EditText field. Have a look at the following image to get an idea of what is the TextWatcher and how that may increase user interactivity. Note that we are going to implement this project using the Java language. 

TextWatcher in Android

Steps to Implement TextWatcher in Android

Step 1: Create an Empty Activity project

Create an empty activity Android Studio project. 

Refer to Android | How to Create/Start a New Project in Android Studio?. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml

  • Implement the Two edit text fields, one for email and one for the password.
  • Invoke the following code inside the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
 
    <!--this is the email edittext field-->
    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="16dp"
        android:hint="Email"
        android:inputType="textEmailAddress" />
 
    <!--this is the email password field-->
    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/etEmail"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:hint="Password"
        android:inputType="textPassword" />
 
    <!--login button which set to be false for the enabled attribute-->
    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/etPassword"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:enabled="false"
        android:text="LOGIN" />
 
</RelativeLayout>


Output: UI

TextWatcher in Android

Step 3: Working with the MainAcitvity.java file

We can also handle both the EditTexts separately. But in this case, to reduce the lines of code, the callback listener TextWatcher is implemented, and the callback listener object is passed to the addTextChangedListener method for each of the edit text.

Invoke the following code inside the MainActivity.java file comments are added for better understanding.

Java




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    // two edit text fields
    EditText etEmail, etPassword;
 
    // one login button
    Button bLogin;
 
    // implement the TextWatcher callback listener
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 
        }
 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // get the content of both the edit text
            String emailInput = etEmail.getText().toString();
            String passwordInput = etPassword.getText().toString();
 
            // check whether both the fields are empty or not
            bLogin.setEnabled(!emailInput.isEmpty() && !passwordInput.isEmpty());
        }
 
        @Override
        public void afterTextChanged(Editable s) {
 
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register all the UI elements
          // with their appropriate IDs
        etEmail = findViewById(R.id.etEmail);
        etPassword = findViewById(R.id.etPassword);
        bLogin = findViewById(R.id.loginButton);
 
        // set the TextChange Listener for both
          // the edit text fields
        etEmail.addTextChangedListener(textWatcher);
        etPassword.addTextChangedListener(textWatcher);
    }
}


Kotlin




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
 
class MainActivity : AppCompatActivity() {
    // two edit text fields
    var etEmail: EditText? = null
    var etPassword: EditText? = null
 
    // one login button
    var bLogin: Button? = null
 
    // implement the TextWatcher callback listener
    private val textWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            // get the content of both the edit text
            val emailInput = etEmail!!.text.toString()
            val passwordInput = etPassword!!.text.toString()
 
            // check whether both the fields are empty or not
            bLogin.setEnabled(!emailInput.isEmpty() && !passwordInput.isEmpty())
        }
 
        override fun afterTextChanged(s: Editable) {}
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // register all the UI elements
        // with their appropriate IDs
        etEmail = findViewById(R.id.etEmail)
        etPassword = findViewById(R.id.etPassword)
        bLogin = findViewById(R.id.loginButton)
 
        // set the TextChange Listener for both
        // the edit text fields
        etEmail.addTextChangedListener(textWatcher)
        etPassword.addTextChangedListener(textWatcher)
    }
}
// This code is written by Ujjwal Kumar Bhardwaj


Output: Run on Emulator

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments