@Override protected void onDraw(Canvas canvas) { if (isShowNormal) { // 如果是默认样式,直接绘制 if (length() < 1) { drawableDel = null; } this.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, drawableDel, null); super.onDraw(canvas); } else { // 如果不是默认样式,需要将图标绘制在中间 drawableLeft = drawables[0]; float textWidth = getPaint().measureText(getHint().toString()); int drawablePadding = getCompoundDrawablePadding(); int drawableWidth = drawableLeft.getIntrinsicWidth(); float bodyWidth = textWidth + drawableWidth + drawablePadding; canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0); super.onDraw(canvas); } }
监听软键盘@Override public boolean onKey(View v, int keyCode, KeyEvent event) { pressSearch = (keyCode == KeyEvent.KEYCODE_ENTER); if (pressSearch && listener != null) { InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.isActive()) { imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0); } if (event.getAction() == KeyEvent.ACTION_UP) { pressSearch = false; listener.onSearchClick(v); } } return false; }
处理 Touch 事件@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: boolean isClean = (event.getX() > (getWidth() - getTotalPaddingRight())) && (event.getX() < (getWidth() - getPaddingRight())); if (isClean) { setText(""); } break; default: break; } return super.onTouchEvent(event); }
点击屏幕任何地方隐藏软键盘private boolean isShouldHideKeyboard(View v, MotionEvent event) { if (v != null && (v instanceof EditText)) { int[] l = {0, 0}; v.getLocationInWindow(l); int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth(); if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) { // 点击EditText的事件,忽略它。 return false; } else { v.clearFocus(); return true; } } // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点 return false; }