Body
First, the realization effect
Second, the implementation of the Code
Listening for input
/**
* Dynamic Search
*/
Private Textwatcher tbxsearch_textchanged = new Textwatcher () {
Whether the cache was empty in the previous text box
Private Boolean isnull = true;
@Override
public void aftertextchanged (Editable s) {
if (Textutils.isempty (s)) {
if (!isnull) {
Msearchview.setcompounddrawableswithintrinsicbounds (NULL,
NULL, miconsearchdefault, NULL);
IsNull = true;
}
} else {
if (IsNull) {
Msearchview.setcompounddrawableswithintrinsicbounds (NULL,
NULL, miconsearchclear, NULL);
IsNull = false;
}
}
}
@Override
public void beforetextchanged (charsequence s, int start, int count,
int after) {
}
/**
* Change the contents of the list dynamically as the contents of the text box change
*/
@Override
public void ontextchanged (charsequence s, int start, int before,
int count) {
}
};
Touch events
Private Ontouchlistener Txtsearch_ontouch = new Ontouchlistener () {
@Override
public boolean Ontouch (View V, motionevent event) {
Switch (event.getaction ()) {
Case MOTIONEVENT.ACTION_UP:
int CurX = (int) event.getx ();
if (CurX > V.getwidth ()-38
&&! Textutils.isempty (Msearchview.gettext ()) {
Msearchview.settext ("");
int cacheinputtype = Msearchview.getinputtype ();//backup the input type
Msearchview.setinputtype (inputtype.type_null);//Disable soft input
Msearchview.ontouchevent (event);/Call Native Handler
Msearchview.setinputtype (Cacheinputtype);//Restore input type
Return true;//consume touch even
}
Break
}
return false;
}
};
Binding events
Private drawable Miconsearchdefault; Search text box default icon
Private drawable miconsearchclear; Search text box Clear text content icon
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main)
Final Resources res = getresources ();
Miconsearchdefault = res.getdrawable (R.drawable.txt_search_default);
Miconsearchclear = res.getdrawable (r.drawable.txt_search_clear);
Msearchview = (edittext) Findviewbyid (R.id.txtsearch);
Msearchview.addtextchangedlistener (tbxsearch_textchanged);
Msearchview.setontouchlistener (Txtsearch_ontouch);
}
Code Description:
1. Bind the Touch event (analog click event Capture) for the input frame. Click to clear the image by listening to the click area and empty the text box if the area is not empty.
2. For the input box bound text to change the event listener, according to the content Change dynamic settings icon display.
3. Maintain the soft keyboard state after emptying operation.