Android EditText 自定义控件 带消除功能

Android EditText 自定义控件 带消除功能.

/**
 * 增强的EditText<BR>
 * 1.带全部消除按钮
 * 
 * @author Hxuejie hxuejie@126.com
 */
public class SuperEditText extends EditText {

	private final int	MARGIN_RIGHT;

	private Drawable	clearDrawable;
	private boolean		clearable;

	public SuperEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		clearDrawable = context.getResources().getDrawable(R.drawable.clear_button);//清除按钮图片
		MARGIN_RIGHT = context.getResources().getDimensionPixelSize(R.dimen.base_space_l);//清除按钮右边距
		clearable = false;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (!clearable) {
			return;
		}
		//在使用center对齐方式时不加会有显示上的问题,不知道为什么android会对这个赋值?
		int offsetX = getScrollX();
		canvas.translate(offsetX, 0);
		clearDrawable.draw(canvas);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int dw = clearDrawable.getIntrinsicWidth();
		int dh = clearDrawable.getIntrinsicHeight();
		int right = getMeasuredWidth() - MARGIN_RIGHT;
		int left = right - dw;
		int top = (getMeasuredHeight() - dh) / 2;
		int bottom = top + dh;
		clearDrawable.setBounds(left, top, right, bottom);
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction,
			Rect previouslyFocusedRect) {
		super.onFocusChanged(focused, direction, previouslyFocusedRect);
		if (focused) {
			showClearButton();
		} else {
			hideClearButton();
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (clearable && onClearButton(event)) {
				return true;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (clearable && onClearButton(event)) {
				// clear
				this.setText("");
				// play click sound
				playSoundEffect(SoundEffectConstants.CLICK);
				return true;
			}
			break;
		}
		return super.onTouchEvent(event);
	}
	
	/**
	 * 检测是否有点中清除按钮
	 * @param event
	 * @return
	 */
	private boolean onClearButton(MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();
		Rect bounds = clearDrawable.getBounds();
		// double touch size
		bounds.inset(-bounds.width(), -bounds.height());
		return bounds.contains(x, y);
	}

	/**
	 * 显示清除按钮
	 */
	private void showClearButton() {
		clearable = true;
		invalidate();
	}

	/**
	 * 隐藏清除按钮
	 */
	private void hideClearButton() {
		clearable = false;
		invalidate();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值