[android]带删除的自定义编辑框EditTextWithDel
先来效果:
没聚焦
聚焦+为未输入
聚焦+输入文字
使用方式:清单内加入,包名记得改改,背景的方框可以让美工出样式。主要是 edittextwithdel:hint=“请输入电话号码” 。这个提示可以换。
<com.caripower.module.widget.EditTextWithDel
android:id="@+id/filter_edit"
android:layout_width="match_parent"
android:layout_height="34dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="8dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="8dp"
android:background="@drawable/iv_search_rec"
android:drawablePadding="8dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_vertical"
android:imeOptions="actionSearch"
android:orientation="vertical"
android:paddingBottom="1dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="1dp"
android:singleLine="true"
android:textColor="#bbbbbb"
android:textSize="15sp"
edittextwithdel:hint="请输入电话号码"
edittextwithdel:imagewidth="16dp"
edittextwithdel:textColor="#bbbbbb"
edittextwithdel:textSize="15sp" />
在使用EditTextWithDel控件的布局内请在最外围布局添加。下面两个是为了进界面就聚焦问题加的。看具体使用,可修改。
xmlns:edittextwithdel="http://schemas.android.com/apk/res-auto"
android:focusable="true"
android:focusableInTouchMode="true"
value内需要添加attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="edittextwithdel">
<attr name="imagewidth" format="dimension" />
<attr name="textColor" format="reference|color" />
<attr name="textSize" format="dimension" />
<attr name="hint" format="string"></attr>
</declare-styleable>
</resources>
activity内使用方式。
EditTextWithDel etSearchEditer = (EditTextWithDel) findViewById(R.id.filter_edit);
etSearchEditer.setOnKeyListener(etSearchEditerOnKeyListener);
etSearchEditer.setClearAllListener(clearAllListener);
/** 输入键盘 搜索按钮*/
private OnKeyListener etSearchEditerOnKeyListener = new OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
logger.info("KeyEvent.KEYCODE_ENTER"+KeyEvent.KEYCODE_ENTER+"=="+keyCode);
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
//在此按条件搜索,加载跟新搜索后的数据
InputMethodManager imm = (InputMethodManager) v .getContext() .getSystemService(NewGroupSelectPersonActivity.this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
etSearchEditer.clearFocus();
return true;
}
if(keyCode == KeyEvent.KEYCODE_DEL){
String edText = etSearchEditer.getText().toString().trim();
if (TextUtils.isEmpty(edText)) {
//用户点键盘上删除,把文字都删除后,还原刚进页面展示。看需求,也可在次还原数据展示
InputMethodManager imm = (InputMethodManager) v .getContext() .getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
etSearchEditer.clearFocus();
}
return false;
}
return false;
}
};
/** 键盘搜索清空后重新加载所有数据 */
private EditTextWithDel.ClearAllListener clearAllListener = new EditTextWithDel.ClearAllListener() {
@Override
public void clearAll() {
//开放接口 在此可还原原本数据展示
}
};
控件源码 EditTextWithDel
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* 带删除按钮的编辑控件
*
* @author wangyueyao
* @created 2015-4-9
*/
public class EditTextWithDel extends AppCompatEditText {
private final static String TAG = "EditTextWithDel";
private Drawable imgInable;
private Drawable imgAble;
private Drawable imgSearch;
private Drawable imgInit;
private Context mContext;
private ClearAllListener clearAllListener;
float searchSize = 0;
float textSize = 0;
int textColor = 0xFF000000;
String textHint = "搜索";
Drawable mDrawable;
Paint paint;
public EditTextWithDel(Context context) {
super(context);
mContext = context;
InitResource(context, null);
InitPaint();
init();
}
public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
InitResource(context, attrs);
InitPaint();
init();
}
public void setClearAllListener(ClearAllListener clearAllListener) {
this.clearAllListener = clearAllListener;
}
public EditTextWithDel(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
InitResource(context, attrs);
InitPaint();
init();
}
private void InitResource(Context context, AttributeSet attrs) {
TypedArray mTypedArray = context.obtainStyledAttributes(attrs,
R.styleable.edittextwithdel);
float density = context.getResources().getDisplayMetrics().density;
searchSize = mTypedArray.getDimension(
R.styleable.edittextwithdel_imagewidth, 16 * density + 0.5F);
textColor = mTypedArray.getColor(R.styleable.edittextwithdel_textColor,
0xFFbbbbbb);
textSize = mTypedArray.getDimension(
R.styleable.edittextwithdel_textSize, 15 * density + 0.5F);
textHint = mTypedArray.getString(R.styleable.edittextwithdel_hint);
if (textHint == null) {
textHint = "搜索";
}
mTypedArray.recycle();
}
public void setTextHint(String textHint) {
this.textHint = textHint;
}
private void init() {
imgInable = mContext.getResources().getDrawable(R.mipmap.delete_gray);
imgAble = mContext.getResources().getDrawable(R.mipmap.delete);
imgSearch = mContext.getResources().getDrawable(
R.mipmap.btn_search_icon);
imgInit = mContext.getResources().getDrawable(R.drawable.iv_search_rec);
addTextChangedListener(watcher);
setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
setSearchDrawable(hasFocus);
}
});
}
// 文字改变监听事件
private TextWatcher watcher = 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) {
setDrawable();
//clearAll();
}
};
// 设置搜索图片的改变
protected void setSearchDrawable(boolean hasFocus) {
setDrawable();
}
// 设置删除图片
private void setDrawable() {
if (hasFocus()) {
if (length() < 1) {
setCompoundDrawablesWithIntrinsicBounds(imgSearch, null,
imgInable, null);
}
else {
setCompoundDrawablesWithIntrinsicBounds(imgSearch, null,
imgAble, null);
}
}
}
private void clearAll() {
if (length() == 0) {
if(clearAllListener != null) clearAllListener.clearAll();
}
}
// 处理删除事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
Log.e(TAG, "eventX = " + eventX + "; eventY = " + eventY);
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 100;
if (rect.contains(eventX, eventY)){
if(!TextUtils.isEmpty(getText().toString())){
setText("");
if(clearAllListener != null) clearAllListener.clearAll();
}
setText("");
clearFocus();
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
// 初始化画笔
private void InitPaint() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(textColor);
paint.setTextSize(textSize);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
DrawSearchIcon(canvas);
}
private void DrawSearchIcon(Canvas canvas) {
if (!hasFocus()) {
if (this.getText().toString().length() == 0) {
float textWidth = paint.measureText("" + textHint);
float textHeight = getFontLeading(paint);
float dx = (getWidth() - searchSize - textWidth - 8) / 2;
float dy = (getHeight() - searchSize) / 2;
canvas.save();
canvas.translate(getScrollX() + dx, getScrollY() + dy);
if (mDrawable != null) {
mDrawable.draw(canvas);
}
canvas.drawText(
"" + textHint,
getScrollX() + searchSize + 8,
getScrollY()
+ (getHeight() - (getHeight() - textHeight) / 2)
- paint.getFontMetrics().bottom - dy , paint);
canvas.restore();
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mDrawable == null) {
try {
mDrawable = getContext().getResources().getDrawable(
R.mipmap.btn_search_icon);
mDrawable.setBounds(0, 0, (int) searchSize, (int) searchSize);
} catch (Exception e) {
}
}
}
@Override
protected void onDetachedFromWindow() {
if (mDrawable != null) {
mDrawable.setCallback(null);
mDrawable = null;
}
super.onDetachedFromWindow();
}
public float getFontLeading(Paint paint) {
FontMetrics fm = paint.getFontMetrics();
return fm.bottom - fm.top;
}
//清空监听器
public interface ClearAllListener{
public void clearAll();
}
}
顺便提供个图片,可以自己换掉的
delete.png
delete_gray.png
iv_search_rec.9.png