效果圖:
直接擼代碼:
public class SearchEditText extends EditText {
private static final String TAG = "SearchEditText";
private Drawable searchImg, delImg;
public SearchEditText(Context context) {
super(context);
init();
}
public SearchEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SearchEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public SearchEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
int pxDimension = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
getContext().getResources().getDisplayMetrics());
setPadding(pxDimension, 0, pxDimension, 0);
searchImg = getContext().getResources().getDrawable(R.drawable.ic_search_red_500_24dp);
delImg = getContext().getResources().getDrawable(R.drawable.ic_delete_forever_red_500_24dp);
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 s) {
setDrawables();//內(nèi)容變換后
}
});
setDrawables();
}
private void setDrawables() {
if (length() < 1) {
setCompoundDrawablesWithIntrinsicBounds(searchImg, null, null, null);
} else {
setCompoundDrawablesWithIntrinsicBounds(searchImg, null, delImg, null);
Drawable[] compoundDrawables = getCompoundDrawables();
// 0 ,1 ,2, 3對應(yīng)左钞诡,上伐坏,右哨啃,下
//如果圖片小可以拉伸下,代碼如下
// Rect bounds = compoundDrawables[2].getBounds();
// int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2,
// getContext().getResources().getDisplayMetrics());
// compoundDrawables[2].setBounds(bounds.left, bounds.top, bounds.right + size, bounds.bottom + size);
// setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2], compoundDrawables[3]);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Drawable[] compoundDrawables = getCompoundDrawables();
if (compoundDrawables[2] != null && event.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 100;
if (rect.contains(eventX, eventY)) {
setText("");
}
}
return super.onTouchEvent(event);
}
}
布局文件就不貼上了,用到的圖片資源也貼上芜繁,有需要的可以下載試試