Home » Android » How to add more than one text changed listener in a layout?

How to add more than one text changed listener in a layout?

Posted by: admin November 1, 2017 Leave a comment

Questions:

In code I would just do:

myEditText.addTextChangedListener(firstTextWatcher);
myEditText.addTextChangedListener(secondTextWatcher);

In xml this works:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:addTextChangedListener="@{viewModel.firstTextWatcher}"/>

However this:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:addTextChangedListener="@{viewModel.firstTextWatcher}"
    app:addTextChangedListener="@{viewModel.secondTextWatcher}"/>

results in:

Duplicate attribute addTextChangedListener

Do you know why is that a problem? I’m using MVVM, so I would like to benefit from data binding. I know that I could combine those two TextWatchers into one but is it really necessary?

Answers:

You also want to give the EditTexts an ID, which can be done in the XML like this: android:id="@+id/box1"

Instead of doing this in the XML file, you want to do this in Java. Here is all the code snips you will need, but you have to place them! You will also need to duplicate these for the second EditText as this is just for one:

private EditText box1;

final EditText box1 = (EditText) findViewByID(R.id.box1);

box1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(final CharSequence txt,int s, int b, int c) {

    }
});

This should work. In the text changed, the int s, int b, and int c is what I am not sure it does. I just used this method below to type this: https://developer.android.com/reference/android/text/TextWatcher.html