I use TextWatcher to listen for key input. When the user enters "@", I open the list, and the user must select from the list. After selection, I put the selected text of the element (including the start @) in the edittext, and normal editing continues.
The problem is that when I click backspace, the line that I get after the aftertextchanged event is incorrect and the activity list appears again.
editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { String str = s.toString(); if (str.length() > 0) { if (str.substring(str.length() - 1).equals("@")) { Intent i = new Intent(MessageComposeActivity.this, MembersListActivity.class); startActivityForResult(i, Util.MEMBERS_LIST); } } } });
And in onActivityResult:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Util.MEMBERS_LIST) if (resultCode == RESULT_OK) { editText.setText(editText.getText().toString() + data.getExtras().get("screenname") + " "); editText.setSelection(editText.getText().length()); } }
For instance:
In EditText, I type '@' and the action pops up and I select 'James'. EditText now displays @James. If I click back once or twice, the activity list reappears and the EditText shows @Jam.
PS: AfterTextChanged () is called twice for the backspace (or any key), the second time afterTextChanged () is executed, I get the wrong input line. The first time I execute afterTextChanged (), I get @Jam, and in the second execution I get "@", so an activity list appears.
Question: Why afterTextChanged () is called twice, and why on the second run I get the wrong text?
Thank you very much.