Preface
Result of this article: when the input text box is empty, the input icon is displayed. If it is not empty, the empty icon is displayed. Click the clear icon to clear the input text in the text box.
Body
I. Implementation results
II. Implementation Code
Bind eventCopy codeThe Code is as follows: private Drawable mIconSearchDefault; // The default icon of the search text box.
Private Drawable mIconSearchClear; // clear text content icon in the search text box
@ 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.txt Search );
MSearchView. addTextChangedListener (tbxSearch_TextChanged );
MSearchView. setOnTouchListener (txtSearch_OnTouch );
}
Touch eventCopy codeThe Code is as follows: 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;
}
};
Copy codeThe Code is as follows: // listen for Input
/**
* Dynamic search
*/
Private TextWatcher tbxSearch_TextChanged = new TextWatcher (){
// Whether the last cached text box is empty
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 ){
}
/**
* The list content is dynamically changed as the text box Content Changes
*/
@ Override
Public void onTextChanged (CharSequence s, int start, int before,
Int count ){
}
};
Code Description:
1. Bind a touch event to the input box (simulate Click Event capture ). You can check whether the image is cleared by monitoring the click area. If the image is in this area and the text box is not empty, the text box is cleared.
2. Bind a text change event listener to the input box and dynamically set the icon Display Based on the content changes.
3. Maintain the soft keyboard status after the clear operation.