まず、テキスト変更リスナーを 1 つ作成SynchronizingWatcherし、両方にアタッチしEditTextます。次に、テキスト変更イベントを受け取ったら、他のテキスト編集を更新する前に、古いリスナーを登録解除し、テキストを更新して、リスナーを再度有効にします。
class SynchronizingWatcher implements TextWatcher {
Set<EditText> synchronizedViews = new HashSet<EditText>();
public void watchView(EditText view) {
view.addTextChangedListener(this);
synchronizedViews.add(view);
}
public void afterTextChanged(Editable s) {
for (EditText editText : synchronizedViews) {
editText.removeTextChangeListener(this);
editText.setText(s); // Of course you can do something more complicated here.
editText.addTextChangeListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Don't care.
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Don't care.
}
}
...
// Somewhere in your activity:
SyncrhonizingWatcher synchronizingWatcher = new SynchronizingWatcher();
synchronizingWatcher.watchView(myEditText1);
synchronizingWatcher.watchView(myEditText1);
別の解決策:既存のKeyListenerものをデコレートする独自のものを提供しますKeyListener(既存のキーリスナーを取得しeditText.getKeyListener()、デコレータを で設定できますeditText.setKeyListener()。デコレータは の他の編集テキストも更新しonKeyUp()ます。しかし、私はそのようなものをいじらないようにします.