我对onTextChanged()
和EditText
事件处理程序使用onKey()
。我想在输入文本时处理onTextChanged()
,在删除文本时处理onKey()
,即我想处理KEYCODE_DEL
。但是我的onTextchanged()
事件总是会发生。任何人都可以发一些想法。
ed.setOnKeyListener(this);
ed. addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//
});
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEY CODE_ENTER) {
//
});
答案 0 :(得分:3)
我通过使用所有回调函数在TextWatcher()中编写整个逻辑解决了这个问题,因为对于Nexus Devices的SoftKeyBoard,不会触发onKeyListener。 我发布的代码可能对其他人有用
ed.addTextChangedListener(new TextWatcher() {
private String previousDigits, num;
private boolean textChanged = false;
@Override
public void onTextChanged(CharSequence currentDigits, int start,
int before, int count) {
if (!(previousDigits.equalsIgnoreCase(currentDigits.toString()))) {
textChanged = true;
num = getStrippedNumber(currentDigits
.toString());
//getStrippedNumber method is used for getting the numeric digits from the string.
if (num.length() > 6) {
num = ("(" + num.substring(0, 3) + ") "
+ num.substring(3, 6) + "-" + num.substring(6));
} else if (num.length() > 3) {
num = ("(" + num.substring(0, 3) + ") " + num
.substring(3));
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
previousDigits = s.toString();
}
@Override
public void afterTextChanged(Editable s) {
if (textChanged) {
textChanged = false;
mEditPhoneNo.setText(num);
mEditPhoneNo.setSelection(mEditPhoneNo.getText().length());
}
}
});
Thanks Guyz