<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">package com.ulucu.xview; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; /** * Created by lbin on 2015/12/9. */ public class XEditText extends EditText { private DrawableLeftListener mLeftListener ; private DrawableRightListener mRightListener ; final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; public XEditText(Context context, AttributeSet attrs) { super(context, attrs); } public XEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public XEditText(Context context) { super(context); } public void setDrawableLeftListener(DrawableLeftListener listener) { this.mLeftListener = listener; } public void setDrawableRightListener(DrawableRightListener listener) { this.mRightListener = listener; } public interface DrawableLeftListener { public void onDrawableLeftClick(View view) ; } public interface DrawableRightListener { public void onDrawableRightClick(View view) ; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: if (mRightListener != null) { Drawable drawableRight = getCompoundDrawables()[DRAWABLE_RIGHT] ; if (drawableRight != null && event.getRawX() >= (getRight() - drawableRight.getBounds().width())) { mRightListener.onDrawableRightClick(this) ; return true ; } } if (mLeftListener != null) { Drawable drawableLeft = getCompoundDrawables()[DRAWABLE_LEFT] ; if (drawableLeft != null && event.getRawX() <= (getLeft() + drawableLeft.getBounds().width())) { mLeftListener.onDrawableLeftClick(this) ; return true ; } } break; } return super.onTouchEvent(event); } }
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">然后可以写一个自定义监听类。</span>
private class DrawableRightClickListener implements XEditText.DrawableRightListener { @Override public void onDrawableRightClick(View view) { if (!mIsShow) { network_password.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_password, 0, R.mipmap.btn_nosee, 0) ; network_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ; } else { network_password.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_password, 0, R.mipmap.btn_see, 0) ; network_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) ; } mIsShow = !mIsShow ; } }