今日博客
监听EditText的内容变化
是基于监听的事件处理机制,好像前面的点击事件是OnClickListener,文本内容 变化的监听器则是:TextWatcher,
我们可以调用EditText.addTextChangedListener(mTextWatcher); 为EditText设置内容变化监听
实现该类需实现三个方法:
public void beforeTextChanged(CharSequence s, int start,int count, int after);
public void onTextChanged(CharSequence s, int start, int before, int count);
public void afterTextChanged(Editable s);
实现带删除键:
public class DelEditText extends EditText {
private Drawable imgClear;
private Context mContext;
public DelEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
}
private void init() {
imgClear = mContext.getResources().getDrawable(R.drawable.delete_gray);
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
setDrawable();
}
});
}
//绘制删除图片
private void setDrawable(){
if (length() < 1)
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
else
setCompoundDrawablesWithIntrinsicBounds(null, null, imgClear, null);
}
//当触摸范围在右侧时,触发删除方法,隐藏叉叉
@Override
public boolean onTouchEvent(MotionEvent event) {
if(imgClear != null && event.getAction() == MotionEvent.ACTION_UP)