Custom EditText of the Android UI Design series Implement the input box with the Purge function (3) _android

Source: Internet
Author: User
Tags event listener

Recently, the company's products in succession to do upgrades, superior leadership to the task is to optimize the structure of the Code and the project structure, and strive to write the project's exquisite concise, so we fill the project to find redundancy ...

We all know that every project basically has a landing page, in the landing page must be the input box, when we enter data in the input box if the input of the content is incorrect or wrong or want to re-enter, if the keyboard on the deletion of the key to be one to delete, At this point we might just as well have a mark when we click on the tag to clear the content we just entered. This can greatly enhance the user experience, take the landing of QQ, the effect is as follows:

When you click on the small X icon on the right of the password box, the input is emptied, it is really convenient, I have also customized this effect in the project input box and always use it in the project, during which no bugs were found, the previous custom structure is as follows:

The implementation is to use a relativelayout, it contains three controls, both sides of the ImageView control, the middle of the EditText control, when clicked on the right to clear the button to clear the contents of the input box, But recently in doing product optimization feeling before the custom control written in the amount of code is a bit wasteful, obviously Android EditText have drawableleft and Drawableright attributes, why not to use it directly? So I drew a picture on the draft paper with a pen, took time to write a new input box with the same effect, and made a lot of simplification on the code scale.

Well, the old rules, first look at the structure of the project:


Engineering Clearedittext is my new definition with the purge function of the input box, mainly inherited from EditText in order to take advantage of its drawableleft and Drawableright properties, then quickly see its implementation

public class Clearedittext extends EditText implements Textwatcher, Onfocuschangelistener {/** * left and right picture resources 
  * Private drawable left, right; 
  /** * Whether to get focus, default no focus * * Private Boolean hasfocus = false; 
   
  /** * When the finger is raised, the x-coordinate/private int xup = 0; 
  Public Clearedittext {This (context, NULL); Public Clearedittext (context, AttributeSet attrs) {This (context, Attrs, Android.) 
  R.attr.edittextstyle); 
    Public Clearedittext (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); 
  Initwedgits (); /** * Initialize Components * @param attrs * Property set/private void Initwedgits () {try {//Get Dr 
      Awableleft picture, if the Drawableleft property is not defined in the layout file, this value is empty left = Getcompounddrawables () [0]; 
      Gets the Drawableright picture, if the Drawableright property is not defined in the layout file, this value is empty right = Getcompounddrawables () [2]; 
    Initdatas (); 
     catch (Exception e) { E.printstacktrace (); }/** * Initialization data */private void Initdatas () {try {//First display, hide delete icon Setcompounddrawa 
      Bleswithintrinsicbounds (left, NULL, NULL, NULL); 
    Addlisteners (); 
    catch (Exception e) {e.printstacktrace (); 
      }/** * Add event Listener/private void addlisteners () {try {setonfocuschangelistener (this); 
    Addtextchangedlistener (this); 
    catch (Exception e) {e.printstacktrace (); 
 
  @Override public void beforetextchanged (charsequence s, int start, int count, int after) {}  @Override public void ontextchanged (charsequence s, int start, int before, int after) {if (Hasfocus) {if (Textutils.isempty (s)) {//If empty, the delete icon is not displayed setcompounddrawableswithintrinsicbounds (left, NULL, NULL, NUL 
      L); 
        else {//if not NULL, to display the delete icon if (null = right) {right = Getcompounddrawables () [2]; }
        Setcompounddrawableswithintrinsicbounds (left, NULL, right, NULL); @Override public boolean ontouchevent (Motionevent event) {try {switch event.getaction 
        ()) {case MOTIONEVENT.ACTION_UP://Get the X coordinate xup = (int) event.getx () when the finger is raised when clicked; When you click the coordinates to the current input box to the right of the distance is less than equal to Getcompoundpaddingright () of the distance, it is considered to click on the delete icon//getcompoundpaddingright () Description: Returns the Rig 
        HT padding of the view, plus spaces for the right drawable if any. if ((GetWidth ()-Xup) <= getcompoundpaddingright ()) {if (!) 
          Textutils.isempty (GetText (). toString ())) {SetText (""); 
      }} break; 
      Default:break; 
    } catch (Exception e) {e.printstacktrace (); 
  Return Super.ontouchevent (event); @Override public void aftertextchanged (Editable s) {} @Override public void Onfocuschange (View V, bo 
      Olean Hasfocus) {try {This.hasfocus = Hasfocus; 
    catch (Exception e) {e.printstacktrace (); 
 } 
  } 
}

The

Explains the order of execution of the Clearedittext, which first inherits EditText, which means that it has all the features of EditText, and then implements the Textwatcher and Onfocuschangelistener interfaces. Where the interface Onfocuschangelistener is used to listen to whether the current input box gets the focus, we assign the state value of the focus that the current input box obtains to the Hasfocus member variable, and the Hasfocus value is true if the focus is obtained. When you enter content in the input box, the Textwatcher listener is triggered, and the beforetextchanged,ontextchanged and aftertextchanged methods are executed sequentially. And we just need to judge the value of the input box in the OnTextChanged method, if the value of the input frame is not empty, show the empty button small icon, or not display, Set the icon to hide and display the method is to directly call the Setcompounddrawableswithintrinsicbounds method on the line, the specific use of this method is unknown, basically that is according to our given picture size picture to the input box in four directions, If the passed-in value is null, it indicates that it is not drawn.

The next step is to empty the small icon to monitor, I first thought is that if the empty small icon is displayed, he set up event monitoring such as Onclicklistener or Ontouchlistener, Unfortunately, the API did not find EditText to provide drawleft or Drawright event monitoring, but also to customize a listener but think about it and complicate the code, In fact, EditText is indirectly inherited view and there is a ontouchevent method in view, we can rewrite the Ontouchevent method and in it according to our fingers pressed or raised coordinates to judge, If the distance to the right of the current control is less than equal to the width of the small icon on the right side of the current control plus the value of paddingright, then we can think of the current control as being emptied by clicking the Clear Small icon. Luckily EditText gave us a way I now think is very real: getcompoundpaddingright (), the interpretation of the document is: Returns the right padding of the view, plus spaces for The right drawable if any. Its value is to empty the small icon width plus paddingright value, hehe, have it to do much more, (*^__^*) Xi hee ...

OK, let's take a look at how to use it in the layout file (it's very simple, just like the EditText method, (*^__^*) Hee ... )

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" 
  Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " android:background= "#ffffff" > <textview android:layout_width= "fill_parent android:layout_height=" wrap _content "android:layout_margin=" 10dip "android:text=" "@string/hello" android:gravity= "Center" android: Textsize= "20SP" android:textcolor= "#000000"/> <com.llew.e.clear.view.wedgit.clearedittext android: Id= "@+id/clearedittext" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:lay 
    Out_margin= "10dip" android:paddingright= "8dip" android:paddingtop= "5dip" android:paddingbottom= "5dip"  
    Android:hint= "Please enter QQ number" android:background= "@drawable/pay_widget_input" android:drawableleft= "@drawable/super_qq" Android:drawableright= "@drawable/clear_normal_list "/> </LinearLayout> 
 

is to write complete our custom package name on the line, attributes are all in the parent class, thanks again Java to provide us with the inheritance characteristics, hehe,
Before running or paste out the mainactivity code, in fact, really very simple:

The public class Mainactivity extends activity {/** called the ' when ' is the ' The activity ' is a 
  -a-created 
  c void OnCreate (Bundle savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
  } 
 

Easy, huh? Create the project automatically generated, do not have any operation, hehe
Okay, let's run it and look at the effect chart O (∩_∩) o~

Before entering:

After entering:

After clicking the clear icon:



Oh, this effect is the same as before, and in terms of the amount of code is less than the previous reduction of a lot, happy

Well, today's custom clearedittext is here, thanks for watching.

SOURCE Download: Android UI implementation with clear function of the input box

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.