0
点赞
收藏
分享

微信扫一扫

自定义View——带清空文本的功能的ClearEditText


EditText增加一个快速清除所有文本的功能。思路:
1、在EditText右边增加一个删除按钮;
2、当EditText输入框有内容时,按钮就显示出来,否则就隐藏。

我们通过继承EditText来自定义一个ClearEditText的方式来实现这个功能。
第一步:在xml布局配置android:drawableEnd或android:drawableRight属性设置我们的清除按钮,如果没有设置,那么我们就使用默认的:

/*同时兼容获取xml布局设置的drawableEnd或drawableRight的图片,如果没有值,则使用默认的*/

drawable = getCompoundDrawablesRelative()[2] == null ? getCompoundDrawables()[2]:getCompoundDrawablesRelative()[2];
if(drawable == null){
drawable = getContext().getResources().getDrawable(R.drawable.ic_backspace_black,null);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}

第二步:在这个图片上添加点击事件,完成清空的功能。但是我们要点击的对象是Drawable,不是View的子类,所以不能注册点击事件,所以我们只能通过onTouchEvent触摸事件,判断触摸的坐标是否落在图片的区域上,以此来做图片的点击事件:

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
/*clear the text of EditText*/
case MotionEvent.ACTION_DOWN:
if (getCompoundDrawables()[2] != null) {
/*the start position of the drawable*/
int start = getWidth() - getTotalPaddingRight() + getPaddingRight();
/*the end position of the drawable*/
int end = getWidth();
/*check if event.getX() is in the range between start and end*/
boolean available = (event.getX() > start) && (event.getX() < end);
if (available) {
this.setText("");
}
}
break;
}
return super.onTouchEvent(event);
}

第三步:当输入框获得焦点时,根据有无文本显示清除按钮:

/**
* Called when the focus state of a view has changed.
*
* @param v The view whose state has changed.
* @param hasFocus The new focus state of v.
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFocus = hasFocus;
if (hasFocus && getText() != null && getText().length() > 0) {
setDrawableVisibility(true);
} else {
setDrawableVisibility(false);
}

}

第四步:监听输入框文本的变化显示清除按钮:

/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* have just replaced old text that had length <code>before</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (hasFocus) {
setDrawableVisibility(s.length() > 0);
}
}

第五步:兼容使用setCompoundDrawablesRelative()和setCompoundDrawables()在代码中设置清除按钮:

@Override
public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) {
super.setCompoundDrawables(left, top, right, bottom);
drawable = right;
if (hasFocus && getText()!=null) {
setDrawableVisibility(getText().toString().length() > 0);
}else {
setDrawableVisibility(false);
}
}

@Override
public void setCompoundDrawablesRelative(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable Drawable bottom) {
super.setCompoundDrawablesRelative(start, top, end, bottom);
drawable = end;
if (hasFocus && getText()!=null) {
setDrawableVisibility(getText().toString().length() > 0);
}else {
setDrawableVisibility(false);
}
}

大功告成!完整的代码如下:

package com.wong.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

import com.wong.spin.R;
import com.wong.utils.CloneUtils;
import com.wong.utils.ObjectUtils;


public class ClearEditText extends AppCompatEditText implements View.OnFocusChangeListener, TextWatcher {
private boolean hasFocus;
private Drawable drawable;

public ClearEditText(Context context) {
super(context);
init(context, null);
}

public ClearEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}

public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}

private void init(Context context, AttributeSet attrs) {

if (attrs != null) {
// TODO 获取xml设置的属性
}
setOnFocusChangeListener(this);
addTextChangedListener(this);
drawable = getCompoundDrawablesRelative()[2] == null ? getCompoundDrawables()[2]:getCompoundDrawablesRelative()[2];
if(drawable == null){
drawable = getContext().getResources().getDrawable(R.drawable.ic_backspace_black,null);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
/*hide the clear button*/
setDrawableVisibility(false);
}


@Override
public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) {
super.setCompoundDrawables(left, top, right, bottom);
drawable = right;
if (hasFocus && getText()!=null) {
setDrawableVisibility(getText().toString().length() > 0);
}else {
setDrawableVisibility(false);
}
}

@Override
public void setCompoundDrawablesRelative(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable Drawable bottom) {
super.setCompoundDrawablesRelative(start, top, end, bottom);
drawable = end;
if (hasFocus && getText()!=null) {
setDrawableVisibility(getText().toString().length() > 0);
}else {
setDrawableVisibility(false);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
/*clear the text of EditText*/
case MotionEvent.ACTION_DOWN:
if (getCompoundDrawables()[2] != null) {
/*the start position of the drawable*/
int start = getWidth() - getTotalPaddingRight() + getPaddingRight();
/*the end position of the drawable*/
int end = getWidth();
/*check if event.getX() is in the range between start and end*/
boolean available = (event.getX() > start) && (event.getX() < end);
if (available) {
this.setText("");
}
}
break;
}
return super.onTouchEvent(event);
}

/**
* Called when the focus state of a view has changed.
*
* @param v The view whose state has changed.
* @param hasFocus The new focus state of v.
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFocus = hasFocus;
if (hasFocus && getText() != null && getText().length() > 0) {
setDrawableVisibility(true);
} else {
setDrawableVisibility(false);
}

}

/**
* if the length of the characters,show the drawable,or hide it
*/
private void setDrawableVisibility(boolean available) {
Drawable d = available ? drawable : null;
super.setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], d, getCompoundDrawables()[3]);
}

/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* are about to be replaced by new text with length <code>after</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* have just replaced old text that had length <code>before</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (hasFocus) {
setDrawableVisibility(s.length() > 0);
}
}

/**
* This method is called to notify you that, somewhere within
* <code>s</code>, the text has been changed.
* It is legitimate to make further changes to <code>s</code> from
* this callback, but be careful not to get yourself into an infinite
* loop, because any changes you make will cause this method to be
* called again recursively.
* (You are not told where the change took place because other
* afterTextChanged() methods may already have made other changes
* and invalidated the offsets. But if you need to know here,
* you can use {@link Spannable#setSpan} in {@link #onTextChanged}
* to mark your place and then look up from here where the span
* ended up.
*/
@Override
public void afterTextChanged(Editable s) {

}
}

效果:

自定义View——带清空文本的功能的ClearEditText_自定义View

这个清除的按钮可以通过xml布局drawableEnd或drawableRight属性来设置或者通过setCompoundDrawablesRelative()和setCompoundDrawables()方法来设置。

谢谢阅读!


举报

相关推荐

0 条评论