檢測edittext中文字的輸入狀態,清空內容
阿新 • • 發佈:2019-01-06
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by xiaoyee on 4/27/15
* 使用者檢測edittext輸入狀態,如果有內容,那麼顯示清空按鈕,如果沒有內容,則清空
*/
public class InputWatcher implements TextWatcher {
private static final String TAG = "InputWatcher" ;
private Button mBtnClear;
private EditText mEtContainer ;
/**
*
* @param btnClear 清空按鈕 可以是button的子類
* @param etContainer edittext
*/
public InputWatcher(Button btnClear, EditText etContainer) {
if (btnClear == null || etContainer == null) {
throw new IllegalArgumentException("請確保btnClear和etContainer不為空");
}
this.mBtnClear = btnClear;
this.mEtContainer = etContainer;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)) {
if (mBtnClear != null) {
mBtnClear.setVisibility(View.VISIBLE);
mBtnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mEtContainer != null) {
mEtContainer.getText().clear();
}
}
});
}
} else {
if (mBtnClear != null) {
mBtnClear.setVisibility(View.GONE);
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
}