Android Basics Getting Started tutorial--3.5 listening to edittext content changes

Source: Internet
Author: User

Android Basics Getting Started tutorial--3.5 listening to edittext content changes

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section:

In the previous section we have learned the EditText control, how to listen to the contents of the input box changes!
This re-practical development is very practical, in addition, with the next section how to implement EditText password visible
And not visible! OK, start this section!

1. Monitor the content changes of EditText

By the problem, is based on the monitoring of the event processing mechanism, as if the previous click event is onclicklistener, text content
The change of the listener is: textwatcher, we can call Edittext.addtextchangedlistener (Mtextwatcher);
Set content change monitoring for EditText!

Simply put, the implementation of this class requires the implementation of three methods: Textwatcher

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);  

This is triggered in turn in the following cases:
1. Content changes before 2. Changes in content 3. After the content changes
We can rewrite the relevant methods according to the actual needs, generally rewrite more is the third method!
There are many occasions to monitor edittext content changes:
Limit word input, restrict input, etc. ~
Here for everyone to implement a simple custom edittext, after entering the content, there will be a side display a fork of the circle, after the user clicked
You can empty the text box ~, of course you can also do not customize, directly to EditText add Textwatcher and then set the Delete button ~

Realize:

Custom EditText:Deledittext.java

 PackageDemo.com.jay.buttondemo;ImportAndroid.content.Context;ImportAndroid.graphics.Rect;Importandroid.graphics.drawable.Drawable;Importandroid.text.Editable;ImportAndroid.text.TextWatcher;ImportAndroid.util.AttributeSet;ImportAndroid.view.MotionEvent;ImportAndroid.widget.EditText;/** * Created by Coder-pig on 2015/7/16 0016. * * Public  class deledittext extends EditText {    PrivateDrawable Imgclear;PrivateContext 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 (NewTextwatcher () {@Override             Public void beforetextchanged(Charsequence S,intStartintCountintAfter) {}@Override             Public void ontextchanged(Charsequence S,intStartintBefore,intCount) {}@Override             Public void aftertextchanged(Editable Editable)            {setdrawable ();    }        }); }//Draw Delete picture    Private void setdrawable(){if(Length () <1) Setcompounddrawableswithintrinsicbounds (NULL,NULL,NULL,NULL);ElseSetcompounddrawableswithintrinsicbounds (NULL,NULL, Imgclear,NULL); }//When the touch range is on the right, the Delete method is triggered and the fork is hidden    @Override     Public Boolean ontouchevent(Motionevent event) {if(Imgclear! =NULL&& event.getaction () = = motionevent.action_up) {intEventx = (int) event.getrawx ();intEventy = (int) Event.getrawy (); Rect rect =NewRect ();            Getglobalvisiblerect (rect); Rect.left = Rect.right- -;if(Rect.contains (Eventx, Eventy)) SetText (""); }return Super. Ontouchevent (event); }@Override    protected void Finalize()throwsThrowable {Super. Finalize (); }}

EditText background drawable:bg_frame_search.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 "> <demo. com. Jay. Buttondemo. DeledittextAndroid: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~ with delete button"Android:maxlength="a"android:padding="5DP"Android:singleline="true"/></linearlayout>

PS: The code is very simple, it does not explain the ~

2. Implement EditText's password visible and invisible

This is also a very practical requirement, that is, the user click on the button can make the password in the edittext visible or invisible ~

Realize:

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" />     <buttonandroid:id="@+id/btnchange"android:layout_width="0DP"  android:layout_weight="1"android:layout_height="48DP"android: Text="password visible"/>                                        </linearlayout>

Mainactivity.java

 PackageCom.jay.demo.edittextdemo;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.text.method.HideReturnsTransformationMethod;ImportAndroid.text.method.PasswordTransformationMethod;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText; Public  class mainactivity extends appcompatactivity {    PrivateEditText edit_pawd;PrivateButton Btnchange;Private BooleanFlag =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 No line breakBtnchange.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View view) {if(Flag = =true) {Edit_pawd.settransformationmethod (hidereturnstransformationmethod.getinstance ()); Flag =false; Btnchange.settext ("Password is 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 --      <strokeandroid:width="1px"android:color="#FFFFFF" />                           <!--set a bottom margin to make the space a little more--      <paddingandroid:bottom="5DP"android:left="5DP"android: right ="5DP"android:top="5DP" />                                          </shape>  
This section summarizes:

This section is here, thank you ~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--3.5 listening to edittext content changes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.