Android Input Box control Clearedittext implementation Cleanup _android

Source: Internet
Author: User
Tags gettext

This article to bring you a very useful small control clearedittext, is in the Android system input box to the right to add a small icon, click on the small icon to clear the contents of the input box, iOS above directly set a property can achieve this function, But Android native EditText does not have this feature, so in order to implement this feature we need to rewrite edittext, and then we'll take you to this little function
We know that we can set the picture for our input box up and down, so we can use the attribute android:drawableright to set our delete small icons, as shown in

I set the left and right side of the picture, if we can set the right side of the picture to monitor, click on the right side of the picture to clear the contents of the input box and hide the deletion icon, this kind of small function will be solved, but Android does not allow us to the right small icon plus the function Is this the way you find out this road is not, in fact, we may simulate the click event, using the input box Ontouchevent () method to simulate,
When we touch lift (that is, ACTION_UP) the range is greater than the left side of the input box to the left of the clear icon, small and the left side of the input box to clear the distance to the right of the picture, we think is click to clear the picture, of course, I do not consider the vertical direction, as long as the removal of small icons on the monitor, The other is all right, I'll put the code up, under the explanation

Package com.example.clearedittext; 
Import Android.content.Context; 
Import android.graphics.drawable.Drawable; 
Import android.text.Editable; 
Import Android.text.TextWatcher; 
Import Android.util.AttributeSet; 
Import android.view.MotionEvent; 
Import Android.view.View; 
Import Android.view.View.OnFocusChangeListener; 
Import android.view.animation.Animation; 
Import Android.view.animation.CycleInterpolator; 
Import android.view.animation.TranslateAnimation; 
 
Import Android.widget.EditText; 
   public class Clearedittext extends EditText implements Onfocuschangelistener, Textwatcher {/** * reference to delete button  
  * * Private drawable mcleardrawable; 
  
  /** * Control whether has the focus * * Private Boolean Hasfoucs;  
  Public Clearedittext {This (context, NULL); "Public clearedittext" (context context, AttributeSet attrs) {//It is also important to construct the method, without which many attributes cannot be defined in XML (conte XT, Attrs, Android.  
  R.attr.edittextstyle); } public Clearedittext(Context, AttributeSet attrs, int defstyle) 
    {Super (context, attrs, Defstyle); 
  Init (); private void Init () {//Get edittext drawableright, if not set we use the default picture mcleardrawable = Getcompounddraw  
    Ables () [2]; 
      if (mcleardrawable = = null) {//throw new NullPointerException ("You can add drawableright attributes in XML");  
    mcleardrawable = Getresources (). getdrawable (R.drawable.delete_selector);  
    Mcleardrawable.setbounds (0, 0, mcleardrawable.getintrinsicwidth (), Mcleardrawable.getintrinsicheight ());  
    The default setting hides the icon setcleariconvisible (false);  
    Set focus-Changing listening setonfocuschangelistener (this);  
  Set the input box to change the content of the listening addtextchangedlistener (this); 
   /** * Because we can not set the Click event directly to EditText, so we use to remember the position we pressed to simulate the click event * when we press the position at the edittext width-the icon to the right of the control spacing-the width of the icon and  
    * EditText Width-The distance between the icon and the right side of the control if we click on the icon, the vertical direction is not considered * * @Override public boolean ontouchevent (Motionevent event) { if (EVENT.GEtaction () = = motionevent.action_up) {if (Getcompounddrawables () [2]!= null) {Boolean touchable = even T.getx () > (GetWidth ()-gettotalpaddingright ()) && (Event.getx () < (getwidth ()-Getpaddingri 
         
        Ght ())); 
        if (touchable) {This.settext (""); 
  }} return Super.ontouchevent (event); /** * When Clearedittext focus changes, determine the string length set clear icon display and hide/@Override public void Onfocuschange (View V, 
    Boolean hasfocus) {this.hasfoucs = Hasfocus;  
    if (hasfocus) {setcleariconvisible (GetText (). Length () > 0);  
    else {setcleariconvisible (false);  }/** * Set clear icon display and hide, call setcompounddrawables for EditText draw up * @param visible/protected void  
    Setcleariconvisible (Boolean visible) {drawable right = visible? Mcleardrawable:null; Setcompounddrawables (Getcompounddrawables () [0], Getcompounddrawables() [1], right, Getcompounddrawables () [3]);  /** * The method of callback when the contents of the input box is changed * * @Override public void ontextchanged (charsequence s, int start, 
        int count, int after) {if (Hasfoucs) {setcleariconvisible (s.length () > 0);  
      
  @Override public void beforetextchanged (charsequence s, int start, int count, int after) { 
  @Override public void aftertextchanged (Editable s) {}/** * Set shaking animation * * 
  public void Setshakeanimation () {this.setanimation (Shakeanimation (5)); /** * Shaking animation * @param counts 1 seconds to shake how many under * @return/public static Animation Shakeanimation 
    T counts) {Animation translateanimation = new Translateanimation (0, 10, 0, 0); 
    Translateanimation.setinterpolator (New Cycleinterpolator (counts)); 
    Translateanimation.setduration (1000); 
  return translateanimation; 
 } 
  
  
}

setcleariconvisible () method , set the way to hide and display the purge icon, we are not here to call the Setvisibility () method, Setvisibility () This method is for view, We can call Setcompounddrawables (drawable left, drawable top, drawable right, drawable bottom) to set up and down icons
Setonfocuschangelistener (this) to set the focus of the input box to change the listener, if the input box has the focus, we determine whether the value of the input box is empty, empty to hide the clear icon, otherwise the display
Addtextchangedlistener (This) set the content of the input box to change listening, in fact, very simple, when the contents of the input box changes, we need to deal with the display and hide the small icon, the content length is not 0, we will show, No is hidden, but this requires the input box to have the focus before we change the show or hide, why need focus, for example, we have a login interface, we have saved the username and password, in the login Interface OnCreate (), we put our saved password displayed in the Username input box and password input box, The contents of the input box changed, resulting in the User name input box and password in the box to clear the small icons are shown, this is obviously not the effect we want, so added a whether there is a focus on the judgment
setshakeanimation (), This method is the input frame left and right jitter method, before I saw a similar function in an application, when the user name error, the input box where the jitter, feeling quite fun, in fact, is mainly used to a mobile animation, Then set the rate of change for the animation to sinusoidal

Next we'll use it, the layout of the activity, two of our custom input boxes, a button

<relativelayout 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:backg" round= "#95CAE4" > <com.example.clearedittext.clearedittext android:id= "@+id/username" android:layout _margintop= "60DP" android:layout_width= "fill_parent" android:background= "@drawable/login_edittext_bg" Andr 
    oid:drawableleft= "@drawable/icon_user" android:layout_marginleft= "10dip" android:layout_marginright= "10dip" Android:singleline= "true" android:drawableright= "@drawable/delete_selector" android:hint= "Enter user name" Android:l ayout_height= "Wrap_content" > </com.example.clearedittext.ClearEditText> <com.example.clearedittext. Clearedittext android:id= "@+id/password" android:layout_marginleft= "10dip" android:layout_marginright= "10di 
  P "android:layout_margintop=" 10dip "  android:drawableleft= "@drawable/account_icon" android:hint= "Enter password" android:singleline= "true" ANDROID:PASSW Ord= "true" android:drawableright= "@drawable/delete_selector" android:layout_width= "Fill_parent" Android:lay out_height= "Wrap_content" android:layout_below= "@id/username" android:background= "@drawable/login_edittext_bg" & 
  Gt </com.example.clearedittext.ClearEditText> <button android:id= "@+id/login" android:layout_width= "F" Ill_parent "android:layout_height=" wrap_content "android:layout_marginleft=" 10dip "Android:layout_marginrig ht= "10dip" android:background= "@drawable/login_button_bg" android:textsize= "18sp" android:textcolor= "@andro Id:color/white "android:layout_below=" @+id/password "android:layout_margintop=" 25DP "android:text=" Login "/&gt 
 
; </RelativeLayout>

 
Then is the interface code writing, mainly testing the input box around the shaking, relatively simple

Package com.example.clearedittext; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.text.TextUtils; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
 
Import Android.widget.Toast; 
 
  public class Mainactivity extends activity {private Toast mtoast; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.activity_main); 
    Final Clearedittext username = (clearedittext) Findviewbyid (r.id.username); 
     
    Final Clearedittext password = (clearedittext) Findviewbyid (R.id.password);  (Button) Findviewbyid (r.id.login). Setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {if (Textutils.isempty (Username.gettext ())) {//set sloshing Username.setshakeanima 
          tion (); 
          Set prompt Showtoast ("User name cannot be empty"); 
        Return }
         
        if (Textutils.isempty (Password.gettext ())) {password.setshakeanimation (); 
          Showtoast ("Password cannot be blank"); 
        Return 
  } 
      } 
    }); 
      /** * Display Toast message * @param msg/private void Showtoast (String msg) {if (mtoast = = null) { 
    Mtoast = Toast.maketext (This, MSG, toast.length_short); 
    }else{Mtoast.settext (msg); 
  } mtoast.show ();  } 
 
 
}

Run the project, such as the picture, tragedy, no animation effect, let's just like this, you are not also want to add it to your project, hurry up!

This is the entire content of this article, I hope to learn more about Android software programming help.

Related Article

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.