0

I'm trying to user TextWatcher interface in order to detect which EditText was changed. I have an activity with 10 EditTexts, and it looks weird to use 10 TextWatchers for each one of them.

There is any way to use only one TextWatcher and to use switch statement on the Editable in the functions afterTextChanged?

galvan
  • 7,400
  • 7
  • 38
  • 55
  • 1
    You should definitely check out [this solution](http://stackoverflow.com/a/13787221/1018177). It uses a single `TextWatcher` for multiple `EditText`s. – Matthias Robbers Mar 06 '13 at 16:37

2 Answers2

0

What I would do is to create a class that extends EditText and create a TextWatcher in that class. You can then implement those EditTexts in your XML or create them programmatically in Java with the TextWatcher listening for each EditText.

Don't know if this will work for you but you can give it a try.

the-ginger-geek
  • 7,041
  • 4
  • 27
  • 45
0

I have never tried this before, but it should work if you check if the EditText is in focus. There are a few ways to go about this and the most straightforward one is to check the focus of the EditText inside your TextWatcher methods. You'll need to do something like this:

if(mEdit1.hasFocus()) {
  ...
} else if(mEdit2.hasFocus()) {
  ...
} else if(mEdit3.hasFocus()) {
  ...
}

A different approach would be to use an OnGlobalFocusChangeListener on your root view and set a variable indicating with EditText currently has focus. It would still require a lot of if statements to check for which EditText has the focus, but may be a more reusable solution.

ebarrenechea
  • 3,775
  • 1
  • 31
  • 37
  • So I have to implement OnFocusChangeListener as well? – galvan Mar 06 '13 at 16:24
  • No, you just need to implement it in once. Either do it inside your `TextWatcher` (or in a helper method) or do it inside the `OnGlobalFocusChangeListener`. – ebarrenechea Mar 06 '13 at 16:28