Are your views polluted with TextWatchers that only implement one of the three methods? Solution: Adapterize!

Problem

This isn’t a big problem; more of an annoyance. You’ll often see this in your code:

EditText nameField = (EditText) findViewById(R.id.name_field);
nameField.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.d(TAG, "Name edited: " + s.toString());
        presenter.onNameChanged(s.toString());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Do nothing.
    }

    @Override
    public void afterTextChanged(Editable s) {
        // Do nothing.
    }
});

See what’s going on? We have to implement the two other methods yet we don’t need them at all. Let’s write a small adapter class to tackle this.

Adapter class for your TextWatchers

A simple solution for this is to write an adapter class that implements the interface:

public abstract class TextWatcherAdapter implements TextWatcher {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // Do nothing here; override when needed.
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Do nothing here; override when needed.
    }

    @Override
    public void afterTextChanged(Editable s) {
        // Do nothing here; override when needed.
    }
}

As you see, we now have an abstract class that implements the interface. To put this to use, let’s change our original code to use this:

EditText nameField = (EditText) findViewById(R.id.name_field);
nameField.addTextChangedListener(new TextWatcherAdapter() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.d(TAG, "Name edited: " + s.toString());
        presenter.onNameChanged(s.toString());
    }
});

There we go! We can implement just the methods we need. Often times you’ll just need one of them, and this will definitely help you out to keep your views a tad cleaner.