Easy Tutorial
❮ Android Tutorial Fragment Demo4 Bit Operation ❯

3.5 Listening to Changes in EditText Content

Category Android Basic Tutorial

Introduction:

In previous sections, we have already learned about the EditText widget. This section will discuss how to listen for changes in the content of the input box! This is very practical in actual development. Additionally, we will briefly talk about how to make the EditText password visible or invisible. Let's get started with this section!


1. Listening to Changes in EditText Content

>

As the title suggests, this is based on an event listening mechanism. Similar to the click event using OnClickListener, the listener for text content changes is TextWatcher. We can call EditText.addTextChangedListener(mTextWatcher) to set up a content change listener for EditText!

Briefly, TextWatcher requires the implementation of three methods:

public void beforeTextChanged(CharSequence s, int start, int count, int after);   
public void onTextChanged(CharSequence s, int start, int before, int count);
public void afterTextChanged(Editable s);

These methods are triggered in the following scenarios:

You can override these methods based on your needs, with the third method being the most commonly overridden.

There are many scenarios for listening to EditText content changes: limiting the number of characters entered, restricting the input content, etc.

Here, we will implement a simple custom EditText. After inputting content, a circle with a cross will appear on the side. Users can click it to clear the text box. Of course, you can also directly add a TextWatcher to the EditText and set a delete button.

Implementation Effect Diagram:

Custom EditText: DelEditText.java

package demo.com.jay.buttondemo;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

/**
 * Created by coder-pig on 2015/7/16 0016.
 */
public class DelEditText extends EditText {

    private Drawable imgClear;
    private Context mContext;

    public DelEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    private void init() {
        imgClear = mContext.getResources().getDrawable(R.drawable.delete_gray);
        addTextChangedListener(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) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setDrawable();
            }
        });
    }

    // Draw the delete image
    private void setDrawable() {
        if (length() < 1)
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        else
            setCompoundDrawablesWithIntrinsicBounds(null, null, imgClear, null);
    }

    // Trigger the delete method when the touch range is on the right side, hiding the cross
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgClear != null && event.getAction() == MotionEvent.ACTION_UP) {
            int eventX = (int) event.getRawX();
            int eventY = (int) event.getRawY();
            Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 100;
            if (rect.contains(eventX, eventY))
                setText("");
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

}

EditText background drawable: bgframesearch.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/background_white" />
    <corners android:radius="5dp" />
    <stroke android:width="1px" android:color="@color/frame_search"/>
</shape>

Color resources: color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="reveal_color">#FFFFFF</color>
    <color name="bottom_color">#3086E4</color>
    <color name="bottom_bg">#40BAF8</color>
    <color name="frame_search">#ADAEAD</color>
    <color name="background_white">#FFFFFF</color>
    <color name="back_red">#e75049</color>
</resources>

Layout file: activity_main.xml

<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:background="@color/back_red"
    android:orientation="vertical"
    tools:context=".MainActivity">

    &lt;demo.com.jay.buttondemo.DelEditText
        android:id="@+id/edit_search"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_margin="10dp"
        android:background="@drawable/bg_frame_search"
        android:hint="带删除按钮的EditText~"
        android:maxLength="20"
        android:padding="5dp"
        android:singleLine="true" />

</LinearLayout>

PS: The code is quite simple and thus not explained in detail.


2. Making EditText Password Visible or Invisible

This is a practical requirement where users can click a button to make the password in the EditText visible or invisible.

Implementation Effect Diagram:

Implementation code: activity_main.xml

<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"
    tools:context=".MainActivity"
    android:layout_margin="5dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/edit_pawd"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="48dp"
        android:inputType="textPassword"
        android:background="@drawable/editborder"/>

    <Button
        android:id="@+id/btnChange"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="48dp"
        android:text="显示密码" />

</LinearLayout>
android:layout_height="48dp"
android:text="Password Visible"/>

</LinearLayout>

MainActivity.java

package com.jay.demo.edittextdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText edit_pawd;
    private Button btnChange;
    private boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit_pawd = (EditText) findViewById(R.id.edit_pawd);
        btnChange = (Button) findViewById(R.id.btnChange);
        edit_pawd.setHorizontallyScrolling(true);    // Set EditText to not wrap
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(flag == true){
                    edit_pawd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flag = false;
                    btnChange.setText("Password Not Visible");
                }else{
                    edit_pawd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flag = true;
                    btnChange.setText("Password Visible");
                }
            }
        });
    }
}

editborder.xml

<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android" >  

    <!-- Set transparent background color -->  
    <solid android:color="#FFFFFF" />  

    <!-- Set a white border -->  
    <stroke  
        android:width="1px"  
        android:color="#FFFFFF" />  
    <!-- Set some padding to make more space -->  
    <padding  
        android:bottom="5dp"  
        android:left="5dp"  
        android:right="5dp"  
        android:top="5dp" />  

</shape>

Summary:

That's it for this section, thank you~

-1.0 Android Basic Beginner Tutorial

-1.0.1 2015 Latest Android Basic Beginner Tutorial Table of Contents

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Using Eclipse + ADT + SDK to Develop Android APP

-1.2.2 Using Android Studio to Develop Android APP

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial for Local Repository Operations

-1.5.2 Git: Setting Up a Remote Repository on GitHub

-1.6 How to Play with 9-Patch Images

-1.7 Interface Prototype Design

-1.8 Project Source Analysis (Various Files, Resource Access)

-1.9 Android Application Signing and Packaging

-1.11 Decompiling APK to Retrieve Code & Resources

-2.1 Concepts of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text Box) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-2.3.3 Button and ImageButton

-2.3.4 ImageView (Image View)

-2.3.5.RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton and Switch

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Drag Bar)

-2.3.9 RatingBar (Star Rating Bar)

-2.4.1 ScrollView (Scroll Bar)

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Adapter Basics

-2.4.5 Simple Usage of ListView

-2.4.6 BaseAdapter Optimization

-2.4.7 ListView Focus Issues

-2.4.8 Solving ListView Checkbox Misalignment Issues

-2.4.9 ListView Data Update Issues

-2.5.0 Building a Reusable Custom BaseAdapter

-2.5.1 Implementing Multi-Layout ListView Items

-2.5.2 Basic Usage of GridView (Grid View)

-2.5.3 Basic Usage of Spinner (List Option Box)

-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Box)

-2.5.5 Basic Usage of ExpandableListView (Collapsible List) ```

-8.3.14 Paint Enumerations/Constants and ShadowLayer Shadow Effect

-8.3.15 Paint API - Typeface (Font Style)

-8.3.16 Canvas API Detailed Explanation (Part 1)

-8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection

-8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh

-8.4.1 Android Animation Collection - Frame Animation

-8.4.2 Android Animation Collection - Tween Animation

-8.4.3 Android Animation Collection - Property Animation - Introduction

-8.4.4 Android Animation Collection - Property Animation - Further Exploration

-9.1 Using SoundPool to Play Sound Effects (Duang~)

-9.2 MediaPlayer for Audio and Video Playback

-9.3 Using Camera to Take Photos

-9.4 Using MediaRecord to Record Audio

-10.1 TelephonyManager (Phone Manager)

-10.2 SmsManager (SMS Manager)

-10.3 AudioManager (Audio Manager)

-10.4 Vibrator (Vibrator)

-10.5 AlarmManager (Alarm Service)

-10.6 PowerManager (Power Service)

-10.7 WindowManager (Window Management Service)

-10.8 LayoutInflater (Layout Service)

-10.9 WallpaperManager (Wallpaper Manager)

-10.10 Sensor Topics (1) - Introduction

-10.11 Sensor Topics (2) - Orientation Sensor

-10.12 Sensor Topics (3) - Accelerometer/Gyroscope Sensor

-10.12 Sensor Topics (4) - Understanding Other Sensors

-10.14 Android GPS Introduction

-11.0《2015最新Android基础入门教程》Completion Celebration~

-12.1 Android Practice: DrySister Viewing Girls App (Version 1) - Project Setup and Simple Implementation

-12.2 DrySister Viewing Girls App (Version 1) - 2. Parsing Backend Data

-12.3 DrySister Viewing Girls App (Version 1) - 3. Image Loading Optimization (Writing an Image Cache Framework)

-12.4 DrySister Viewing Girls App (Version 1) - 4. Adding Data Caching (Introducing SQLite)

-12.5 DrySister Viewing Girls App (Version 1) - 5. Code Review, Adjustment, and Logging Class Writing

-12.6 DrySister Viewing Girls App (Version 1) - 6. Icon Creation, Obfuscation, Signing, APK Slimming, App Release

WeChat Subscription

❮ Android Tutorial Fragment Demo4 Bit Operation ❯