Come modificare il testo textView su datachange senza richiamare il listener di Testowatcher
-
28-10-2019 - |
Domanda
TextView textView=new TextView(context);
textView.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) {
s.append("A");
}
});
Se aggiungiamo un TextWatcher
a a TextView
, e voglio aggiungere una lettera a questo TextView
, ogni volta che l'utente scrive una lettera, ma questo continua a richiamare il TextWatcher
Ascoltatore, così via StackOverFlow error
, quindi come aggiungere un testo senza richiamare il TextWatcher
Ascoltatore?
Soluzione
La documentazione di post -tratteggio dice:
Questo metodo è chiamato per avvisarti che, da qualche parte all'interno di S, il testo è stato modificato. È legittimo apportare ulteriori modifiche a S da questo callback, Ma fai attenzione a non metterti in un ciclo infinito, perché eventuali modifiche apportate causerà nuovamente questo metodo in modo ricorsivo. (Non ti viene detto dove si è verificata la modifica perché altri metodi di post -tratteggio () potrebbero aver già apportato altre modifiche e non validare gli offset. Ma se devi sapere qui, puoi usare setSpan(Object, int, int, int)
in onTextChanged(CharSequence, int, int, int)
Per segnare il tuo posto e poi alzati lo sguardo da qui dove è finita l'intervallo.
Quindi, con ogni s.append("A")
voi call afterTextChanged()
di nuovo e così via.
Altri suggerimenti
È facile:
@Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
//Any modifications at this point will not be detected by TextWatcher,
//so no more StackOverflowError
s.append("A");
editText.addTextChangedListener(this);
}
Un altro modo per evitare lo stackoverflow:
TextView textView=new TextView(context);
textView.addTextChangedListener(new TextWatcher() {
boolean editing=false;
@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) {
if (!editing){
editing=true;
s.append("A");
editing=false;
}
}
});
Versione Kotlin
editText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (s.toString().isNotBlank()) {
val formattedValue: String = // Do some formatting
editText.removeTextChangedListener(this)
editText.setText(formattedValue)
editText.setSelection(editText.text.toString().length)
editText.addTextChangedListener(this)
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})