importandroid.app.Activity;importandroid.content.res.Resources;importandroid.graphics.drawable.Drawable;importandroid.os.Bundle;importandroid.text.Editable;importandroid.text.InputType;importandroid.text.TextUtils;importandroid.text.TextWatcher;importandroid.view.Menu;importandroid.view.MotionEvent;importandroid.view.View;importandroid.view.View.OnTouchListener;importandroid.widget.EditText;importandroid.widget.Toast;public class MainActivity extendsActivity {private Drawable mIconSearchDefault; //搜索文本框默认图标
private Drawable mIconSearchClear; //搜索文本框清除文本内容图标
private EditText mSearchView = null;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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);
}
@Overridepublic booleanonCreateOptionsMenu(Menu menu) {//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);return true;
}/*** 判断输入框中是否有数据,然后显示相应的图标文件*/
private TextWatcher tbxSearch_TextChanged = newTextWatcher() {//缓存上一次文本框内是否为空
private boolean isnull = true;
@Overridepublic voidafterTextChanged(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;
}
}
}
@Overridepublic void beforeTextChanged(CharSequence s, int start, intcount,intafter) {
}/*** 随着文本框内容改变动态改变列表内容*/@Overridepublic void onTextChanged(CharSequence s, int start, intbefore,intcount) {
}
};//当清除图标被点击的时候的处理事件
private OnTouchListener txtSearch_OnTouch = newOnTouchListener() {
@Overridepublic booleanonTouch(View v, MotionEvent event) {switch(event.getAction()) {caseMotionEvent.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
Toast toast = Toast.makeText(MainActivity.this, "你好啊", Toast.LENGTH_SHORT);
toast.show();//type
return true;//consume touch even
}break;
}return false;
}
};
}