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

本文详细介绍了如何在Android应用中实现一个动态搜索框,当文本框为空时显示输入图标,非空时显示清空图标,并允许用户点击清空图标来清除文本。通过监听触摸事件和文本变化,实现了图标与功能的无缝切换,并保持了输入时软键盘的状态。
摘要由CSDN通过智能技术生成

前言

本文实现的效果:文本框输入为空时显示输入的图标;不为空时显示清空的图标,此时点击清空图标能清空文本框内输入文字。

正文

一、实现效果

130525a3426cb332029cad6fad705fea.png

1c2d54e0519ddbc542075992beed2fa4.png

二、实现代码

绑定事件

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.维持清空操作后软键盘状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值