歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> 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

Copyright © Linux教程網 All Rights Reserved