Question: Question:
Good evening.
I'm thinking of detecting the end of input of EditText by detecting the confirmation. I found the following code in the search.
edit1.addTextChangedListener(new TextWatcher()
{
int currentLength = 0;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
currentLength = s.toString().length();
}
@Override
public void afterTextChanged(Editable s) {
Log.v("", "after:" + s.toString());
if (s.toString().length() < currentLength) {
return;
}
boolean unfixed = false;
Object[] spanned = s.getSpans(0, s.length(), Object.class);
if (spanned != null) {
for (Object obj : spanned) {
if (obj instanceof android.text.style.UnderlineSpan) {
unfixed = true;
}
}
}
if (!unfixed) {
Toast toast = Toast.makeText(getApplicationContext(), "確定", Toast.LENGTH_SHORT);
toast.show();
}
}
});
It works fine, but it also happens when I press the Delete key on the soft keyboard after confirming.
Is there a way to prevent this?
Thank you.
Answer: Answer:
As a result of investigation, it seems that the count of onTextChanged(CharSequence s, int start, int before, int count)
becomes 0 when the Delete key of the soft keyboard is input.
So I did the following:
edit1.addTextChangedListener(new TextWatcher() {
boolean keycodeFlag = false; // 上記コードに追加
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// このブロック追加
if (count == 0) {
keycodeFlag = true;
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length() < currentLength || keycodeFlag) { // 変更
keycodeFlag = false; // 追加
return;
}
}
}
Now you can prevent the Delete key in your question from being detected as confirmed.
(Confirmed with Android 4.2.2, 4.4.4, 5.0 on Genymotion emulator)