I want to implement the TextWatcher
interface for more than one EditText
fields. Currently I am using :
text1.addTextChangedListener(this);
text2.addTextChangedListener(this);
then overriding the methods in my Activity:
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// do some operation on text of text1 field
// do some operation on text of text2 field
}
However this is working fine but I'm looking for other ways so that I can explicitly identify that in which EditText
field the SoftKeyboard
is currently focused.
One more way around is to add
OnClickListener
toEditText
and set a global variable as given belowUse this etCurrentEditor as a reference to currently edited EditText
You can do this for getting the id of the edit texts. It's not tested but let me know if it works.
Suggested solution in @Sebastian Roth's answer is not one instance of
TextWatcher
for someEditTexts
. It is one class and n instances of that class for nEditTexts
.Each EditText has its own Spannable.
TextWatcher
's events has this Spannable ass
parameter. I check their hashCode (unique Id of each object). myEditText1.getText() returns that Spannable. So if themyEditText1.getText().hashCode()
equals withs.hashCode()
it means thats
belongs tomyEditText1
So if you want to have one instance of
TextWatcher
for someEditTexts
you should use this:and
Global One class for all the activities.
CustomTextWatcher.java
I use this solution:
Add method that returns listener:
Add listener to multiple EditText's, you can also pass other parameters:
This is what I have done...
Then just added the TextWatcher to each EditText in the onCreate method & also kept the button setEnabled(false) by default here.