很多app的输入框都有一键删除的功能,这样用户体验很好。
今天我就给大家带来两种实现这种功能的方法。
方法一:
1、将EditText边框设置为不可见(android:background=”@null”)
2、将EditText和ImageView(删除图标,这里可以给ImageView设置状态选择器控制点击和抬起效果)放在水平的LinearLayout中
3、给LinearLayout设置背景图片,要求背景图片能够框住两个控件,以达到两控件连接在一起的的效果
4、通过对EditText进行输入监听来控制ImageView的显示、消失、获取和失去焦点。
方法二(简单粗暴,继承EditText重写):
1、 继承EditText
2、通过方法setCompoundDrawablesWithIntrinsicBounds(left,top,right,bottom)在EditText中添加删除图标。
3、通过监听EditText输入设置删除图标的显示和消失。
4、为删除图标添加点击事件,由于删除图标本身不具有点击事件,我们通过Rect来限制用户点击删除的范围,也就是,只有当点击事件落在Rect框住的范围中才实现删除功能。
由于第一种方法的实现很简单,所以我就为大家献上方法2的核心代码。
先来两张程序运行效果如:
输入之前:
输入之后:
我用5.1系统调试的,如果低版本手机调试,输入框可能不是一条下划线,可能是一个把文字框住的框框。
EditTextWithDelete 类(直接放到xml布局文件中即可):
public class EditTextWithDelete extends EditText {
Context context;
Drawable deleteAllOn;//点击抬起时候的删除图标
Drawable deleteAllDown;//点击按下时候的删除图标
public EditTextWithDelete(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
public EditTextWithDelete(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public EditTextWithDelete(Context context) {
super(context);
this.context = context;
init();
}
private void init(){
deleteAllOn = context.getResources().getDrawable(R.drawable.delete);
deleteAllDown = context.getResources().getDrawable(R.drawable.delete_gray);
addTextChangedListener(new TextWatcher(){//监听用户输入
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
setDraw();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void setDraw(){//重绘
if(length() > 1){
setCompoundDrawablesWithIntrinsicBounds(null,null,deleteAllOn,null);
// setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)表示左、上、右、下
}
else{
setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int touchX = (int) event.getRawX();
int touchY = (int) event.getRawY();
int touchX1 = (int) event.getX();
int touchY1 = (int) event.getY();
/*getX()是表示view相对于自身左上角的x坐标,
而getRawX()是表示相对于屏幕左上角的x坐标值
(注意:这个屏幕左上角是手机屏幕左上角,
不管activity是否有titleBar或是否全屏幕)
*/
Rect rect = new Rect();
getGlobalVisibleRect(rect);//用Rect将控件框起来
rect.left = rect.right - 40;//将Rect的范围缩小到图片显示区域,只有点击落在改区域才会删除输入文字
if(length()>1){//当有文字输入时在进行操作
if(rect.contains(touchX, touchY)){
setCompoundDrawablesWithIntrinsicBounds(null,null,deleteAllDown,null);
}else{
setCompoundDrawablesWithIntrinsicBounds(null,null,deleteAllOn,null);
}
if(event.getAction() == MotionEvent.ACTION_UP){
if(rect.contains(touchX, touchY)){
setText("");//清除输入的字符串
}
setDraw();//重绘
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}