先上效果图:
继承EditText使用setCompoundDrawablesWithIntrinsicBounds添加图标,使用onTouchEvent计算触摸的位置。
添加了没有文本的时候图标是否显示跟一开始先明文还是密文的判断。
直接上代码:
public class PswEditText extends EditText {
private static final int EXTRA_AREA = 20;//额外的点击范围
private boolean iconShowWithOutText;
private boolean isIconShow;
private boolean pswVisible;//默认密码是隐藏的
private int showID = R.mipmap.password_show_btn;
private int hideID = R.mipmap.password_hide_btn;
private Drawable showDrawable;
private Drawable hideDrawable;
public PswEditText(Context context) {
this(context, null);
}
public PswEditText(Context context, AttributeSet attrs) {
super(context, attrs);
//获取属性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PswEditText);
iconShowWithOutText = ta.getBoolean(R.styleable.PswEditText_iconShowWithOutText, false);
pswVisible = ta.getBoolean(R.styleable.PswEditText_pswVisible, false);
showDrawable = context.getResources().getDrawable(showID);
hideDrawable = context.getResources().getDrawable(hideID);
ta.recycle();
if (iconShowWithOutText) {
isIconShow = true;
controlDrawable();
controlPswShowOrHide();
}
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) {
if (!iconShowWithOutText) {
if (s.length() > 0) {
isIconShow = true;
controlDrawable();
controlPswShowOrHide();
} else {
isIconShow = false;
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
}
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isIconShow) {
int xDown = (int) event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Rect rectD = getCompoundDrawables()[2].getBounds();
int rectX = getWidth() - rectD.width() - EXTRA_AREA - getPaddingRight();
if (rectX <= xDown) {
pswVisible = !pswVisible;
controlPswShowOrHide();
controlDrawable();
return true;
}
break;
}
}
return super.onTouchEvent(event);
}
private void controlDrawable() {
setCompoundDrawablesWithIntrinsicBounds(null, null, pswVisible ? hideDrawable : showDrawable, null);
}
//控制密码明文或密文
private void controlPswShowOrHide() {
if (pswVisible) {
//明文显示
setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
//密文显示
setTransformationMethod(PasswordTransformationMethod.getInstance());
}
setSelection(getText().toString().length());
}
}
属性:
<declare-styleable name="PswEditText">
<!--没有文本的时候也显示-->
<attr name="iconShowWithOutText" format="boolean"/>
<!--密码开始时是否可看-->
<attr name="pswVisible" format="boolean"/>
</declare-styleable>
直接复制代码就能使用。
如果有什么不对的地方,跪求指正。