Every letter that the user types in EditText
, invokes the function
TextWatcher
which leads to Text-to-speech
.
So if it writes 'c', the app returns a speech saying 'c'. if it then enters 'a', returns 'a'.
The problem is that when the user deletes the last character entered, the app also returns the letter that was before it was deleted.
With the same example, the word formed would be 'ca'. If the user deletes 'a', the app returns 'c'.
I need to do a check of the key pressed to delete, because if it is pressed, it will not be able to trigger text-to-speech
.
editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_DEL){
return true;
}else{
return false;
}
}
});
editTextPrincipal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onKey == false){
editTextPrincipal.addTextChangedListener(textWatcher);
}
}
});
I tried to make this suggested change, but it did not resolve:
editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
keyCode = event.getKeyCode();
if (keyCode != KeyEvent.KEYCODE_DEL){
editTextPrincipal.addTextChangedListener(textWatcher);
return true;
}
return false;
}
});
I know this code is wrong, but the logic I wanted was to call the function onKey
within setOnClickListener
, in that condition of if
.
My TextWatcher:
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
oqSeraFalado = editTextPrincipal.getText().toString();
if (oqSeraFalado.length() > 1){
oqSeraFalado = oqSeraFalado.substring(oqSeraFalado.length()-1);
vamosFalar();
}else{
vamosFalar();
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
public void vamosFalar(){
String ToSpeak = oqSeraFalado;
Toast.makeText(getApplicationContext(), ToSpeak, Toast.LENGTH_SHORT).show();
tts.setPitch(1);
tts.setSpeechRate(1);
tts.speak(ToSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
I discovered something funny ... I made this change in the code:
editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
keyCode = event.getKeyCode();
Log.e("key",keyCode+"");
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
usuarioDeletouCaracter = true;
return usuarioDeletouCaracter;
}
return usuarioDeletouCaracter;
}
});
and in the log, it only takes the delete value from the keyboard only if it has nothing written in the EditText in question. otherwise, it will not take the code from any other key for the var keycode.