[Android]文本框实现搜索和清空效果
16lz
2022-03-23
前言
本文实现的效果:文本框输入为空时显示输入的图标;不为空时显示清空的图标,此时点击清空图标能清空文本框内输入文字。
声明
欢迎转载,但请保留文章原始出处:)
农民伯伯:http://over140.blog.51cto.com/
正文
一、实现效果
二、实现代码
监听输入
/***动态搜索
*/
private TextWatchertbxSearch_TextChanged = new TextWatcher(){
// 缓存上一次文本框内是否为空
private boolean isnull = true ;
@Override
public void afterTextChanged(Editables){
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(CharSequences, int start, int count,
int after){
}
/**
*随着文本框内容改变动态改变列表内容
*/
@Override
public void onTextChanged(CharSequences, int start, int before,
int count){
}
};
触摸事件
private OnTouchListenertxtSearch_OnTouch = new OnTouchListener(){@Override
public boolean onTouch(Viewv,MotionEventevent){
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(); // backuptheinputtype
mSearchView.setInputType(InputType.TYPE_NULL); // disablesoftinput
mSearchView.onTouchEvent(event); // callnativehandler
mSearchView.setInputType(cacheInputType); // restoreinputtype
return true ; // consumetoucheven
}
break ;
}
return false ;
}
};
绑定事件
private DrawablemIconSearchDefault; // 搜索文本框默认图标private DrawablemIconSearchClear; // 搜索文本框清除文本内容图标
@Override
protected void onCreate(BundlesavedInstanceState){
super .onCreate(savedInstanceState);
setContentView(R.layout.main)
final Resourcesres = 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);
}
代码说明:
1. 为输入框绑定触摸事件(模拟点击事件捕捉)。通过监听点击区域判断是否点击清空图片,如果在该区域并且文本框不为空,则清空文本框。
2. 为输入框绑定文本改变事件监听,根据内容改变动态设置图标显示。
3. 维持清空操作后软键盘状态。
三、参考
1. how to block virtual keyboard while clicking on edittext in android?
四、小图标下载
(右键另存为即可。)
结束
活用好每一个控件的属性、方法和事件能实现很多有意思的效果。欢迎大家交流。
更多相关文章
- 看Google官方的Android开发文档的一些收获
- Android高手进阶教程(二)之----Android(安卓)Launcher抽屉类Slid
- 无废话Android之常见adb指令、电话拨号器、点击事件的4种写法、
- android (21)
- [Android]解决Fragment无法使用android:onClick属性
- Android事件总线(三)otto用法全解析
- android XML解析技术
- 【自动化测试】Android(安卓)Monkey实践
- Android事件分发机制浅析