广告
返回顶部
首页 > 资讯 > 移动开发 >Android文本框搜索和清空效果实现代码及简要概述
  • 441
分享到

Android文本框搜索和清空效果实现代码及简要概述

Android 2022-06-06 10:06:34 441人浏览 安东尼
摘要

前言 本文实现的效果:文本框输入为空时显示输入的图标;不为空时显示清空的图标,此时点击清空图标能清空文本框内输入文字。正文 一、实现效果    二、实现代码 绑定事件 代码如

前言
本文实现的效果:文本框输入为空时显示输入的图标;不为空时显示清空的图标,此时点击清空图标能清空文本框内输入文字。
正文
一、实现效果
  
  
二、实现代码
绑定事件
代码如下:
private Drawable mIconSearchDefault; // 搜索文本框默认图标
private Drawable mIconSearchClear; // 搜索文本框清除文本内容图标
@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);
}

触摸事件
代码如下:
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;
}
};

代码如下:
//监听输入

private TextWatcher tbxSearch_TextChanged = new TextWatcher() {
//缓存上一次文本框内是否为空
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) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};

代码说明
1.为输入框绑定触摸事件(模拟点击事件捕捉)。通过监听点击区域判断是否点击清空图片,如果在该区域并且文本框不为空,则清空文本框。
2.为输入框绑定文本改变事件监听,根据内容改变动态设置图标显示。
3.维持清空操作后软键盘状态。 您可能感兴趣的文章:Android实现搜索功能并本地保存搜索历史记录Android SearchView搜索框组件的使用方法Android百度地图实现搜索和定位及自定义图标绘制并点击时弹出泡泡Android 百度地图POI搜索功能实例代码android实现读取、搜索联系人的代码Android拨号盘 支持T9搜索和号码搜索等拨号盘案例Android搜索框通用版Android实现带列表的地图POI周边搜索功能Android搜索框组件SearchView的基本使用方法Android实现搜索本地音乐的方法


--结束END--

本文标题: Android文本框搜索和清空效果实现代码及简要概述

本文链接: https://www.lsjlt.com/news/27971.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作