自定义EditText,实现带删除功能的输入框;
package com.xspacing.register.view;
import com.xspacing.register.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
/**
*
* @ClassName CustomEditText.java
* @Description 自定义EditText
* @author Smile
* @version v1.0
* @date 2016年9月20日 下午9:09:10
*/
public class CustomEditText extends EditText {
private Drawable drawable;
private Context mContext;
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
initEditText();
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initEditText();
}
public CustomEditText(Context context) {
super(context);
mContext = context;
initEditText();
}
private void initEditText() {
// 监听输入框的字符
this.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
getDrawable();
}
});
}
private void getDrawable() {
//获取删除图片
drawable = ContextCompat.getDrawable(mContext, R.drawable.delete);
if (length() >= 1) {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
} else {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
this.requestFocus();// 获取焦点
if (drawable != null && event.getAction() == MotionEvent.ACTION_DOWN) {
float x = event.getX();
if (getWidth() - drawable.getMinimumWidth() <= x && x <= getWidth()) {
this.setText("");
return true;
}
}
return surpe.onTouchEvent(event);
}
}