Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Android实现仿IOS带清空功能的文本输入框

Android实现仿IOS带清空功能的文本输入框/**
* @类名:ClearableEditText
* @功能描述:
* @作者: William Xu
* @创建日期:2013-4-13
* @修改人:
* @修改日期:
* @修改备注:
* @版本号:1.0
*/
public class ClearableEditText extends EditText implements
OnFocusChangeListener, TextWatcher {private Drawable xD;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();
}private void init() {
xD = getCompoundDrawables()[2];
if (xD == null) {
xD = getResources()
.getDrawable(R.drawable.search_clear);
}
xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnFocusChangeListener(this);
addTextChangedListener(this);
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener f) {
this.f = f;
}private OnFocusChangeListener f;@Override
public boolean onTouchEvent(MotionEvent event) {
if (getCompoundDrawables()[2] != null) {
if (event.getAction() == MotionEvent.ACTION_UP) {
boolean tappedX = event.getX() > (getWidth()
- getPaddingRight() - xD.getIntrinsicWidth());
if (tappedX) {
setText("");event.setAction(MotionEvent.ACTION_CANCEL);}
}
}return super.onTouchEvent(event);
}@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
if (f != null) {
f.onFocusChange(v, hasFocus);
}
} protected void setClearIconVisible(boolean visible) {
Drawable x = visible ? xD : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], x, getCompoundDrawables()[3]);
}@Override
public void onTextChanged(CharSequence s, int start, int count,
int after) {
setClearIconVisible(s.length() > 0);
}@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub}@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub}
}更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11