12-27 自定义好看的搜索界面(附带搜索动画)

输入前,输入后界面样式如图:



首先自定义EditText

```

/**

* @author bmy

* @auto

* @des :带删除按钮的EditText

*/

public class ClearEditTextextends AppCompatEditText implements View.OnFocusChangeListener, TextWatcher {

private boolean hasFocus =false;

    private DrawablemClearDrawable =null;

    public ClearEditText(Context context, AttributeSet attrs) {

super(context, attrs, android.R.attr.editTextStyle);

        this.init();

    }

private void init() {

mClearDrawable =this.getCompoundDrawables()[2];

        if (mClearDrawable ==null) {

mClearDrawable =this.getResources().getDrawable(R.mipmap.ic_action_clear);

        }

mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());

        // 默认设置隐藏图标

        this.setClearIconVisible(false);

        // 设置焦点改变的监听

        this.setOnFocusChangeListener(this);

        // 设置输入框里面内容发生改变的监听

        this.addTextChangedListener(this);

    }

@Override

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

}

@Override

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

if (charSequence !=null &&this.hasFocus) {

setClearIconVisible(charSequence.length() >0);

        }

}

@Override

    public void afterTextChanged(Editable editable) {

}

@Override

    public void onFocusChange(View view, boolean hasfocus) {

this.hasFocus = hasfocus;

        if (hasFocus) {

setClearIconVisible(this.getText().length() >0);

        }else {

setClearIconVisible(false);

        }

}

private void setClearIconVisible(Boolean visible) {

Drawable right = visible ?mClearDrawable :null;

        setCompoundDrawables(this.getCompoundDrawables()[0],

                this.getCompoundDrawables()[1], right, this.getCompoundDrawables()[3]);

    }

@Override

    public boolean onTouchEvent(MotionEvent event) {

if (event.getAction() == MotionEvent.ACTION_UP) {

if (this.getCompoundDrawables()[2] !=null) {

int x = (int) event.getX();

                int y = (int) event.getY();

                Rect rect =this.getCompoundDrawables()[2].getBounds();

                int height = rect.height();

                int distance = (getHeight() - height) /2;

                boolean isInnerWidth = x > getWidth() - getTotalPaddingRight() && x < getWidth() - getPaddingRight();

                boolean isInnerHeight = y > distance && y < distance + height;

                if (isInnerWidth && isInnerHeight) {

this.setText("");

                }

}

}

return super.onTouchEvent(event);

    }

}

```

DEMO 地址详见:https://github.com/BuMiangYang/BronzeDemo

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容