getCompoundDrawables
方法简介:
用于获取当下该控件的上下左右位置的Drawable引用,该方法返回的是Drawable[]数组,length为4,分别对应Left,Top,Right和Bottom的Drawable引用。比如:以下代码的Edittext,drawable[2]就对应于EditText控件的右端。在代码中动态添加图标就用到这个方法,相当于XML文件中的drawableRight。
代码:
public class ClearableEditText extends EditText implements View.OnTouchListener,View.OnFocusChangeListener,TextWatcher {
public interface Listener {
void didClearText();
}
public void setListener(Listener listener) {
this.listener = listener;
}
private Drawable xD;
private Listener listener;
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context,AttributeSet attrs) {
super(context,attrs);
init();
}
public ClearableEditText(Context context,AttributeSet attrs,int defStyle) {
super(context,attrs,defStyle);
init();
}
@Override
public void setOnTouchListener(OnTouchListener l) {
this.l = l;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener f) {
this.f = f;
}
private OnTouchListener l;
private OnFocusChangeListener f;
@Override
public boolean onTouch(View v,MotionEvent event) {
if (getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - xD
.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
setText("");
if (listener != null) {
listener.didClearText();
}
}
return true;
}
}
if (l != null) {
return l.onTouch(v,event);
}
return false;
}
@Override
public void onFocusChange(View v,boolean hasFocus) {
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
if (f != null) {
f.onFocusChange(v,hasFocus);
}
}
@Override
public void onTextChanged(CharSequence s,int start,int before,int count) {
if (isFocused()) {
setClearIconVisible(getText().length() > 0);
}
}
@Override
public void beforeTextChanged(CharSequence s,int count,int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
private void init() {
xD = getCompoundDrawables()[2];
if (xD == null) {
xD = getResources()
.getDrawable(android.R.drawable.presence_offline);
}
xD.setBounds(0,0,xD.getIntrinsicWidth(),xD.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnTouchListener(this);
super.setOnFocusChangeListener(this);
addTextChangedListener(this);
}
protected void setClearIconVisible(boolean visible) {
boolean wasVisible = (getCompoundDrawables()[2] != null);
if (visible != wasVisible) {
Drawable x = visible ? xD : null;
setCompoundDrawables(getCompoundDrawables()[0],getCompoundDrawables()[1],x,getCompoundDrawables()[3]);
}
}
}
拓展:
loginPswEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//隐藏密码
loginPswEt.setTransformationMethod(PasswordTransformationMethod.getInstance());//显示密码
此至!