1

This is a question for a generic problem with Android developing I would like to solve. Sometimes you have multiple buttons/text views etc that all need almost the same listener attached. The only difference being that each button/view is associated with a different field variable. Therefore the listener for each of the UI elements all have the exact same code except for which field variables are accessed/changed.

A horrible way of accomplishing this is to just make a lot of code duplication so you copy the code for the listener for each of the buttons and only changing the needed variables but this is obviously horrendous solution.

I tried to make a listener creator method that returned an anonymous listener class but could not figure out how to pass the relevant field variables as arguments to the creator method such that the anonymous listeners could use them.

How can this problem be solved in a good way?

Matias Frank Jensen
  • 497
  • 1
  • 5
  • 11
  • Maybe [this](https://stackoverflow.com/questions/16785922/creating-the-instance-of-abstract-class-or-anonymous-class) will help. Can you post a horrible example? – Andrew S Oct 30 '17 at 18:42
  • Preferably two or three examples of _almost the same listener_? The easiness of abstraction of these listeners depends greatly on what kind of operation they do with these _fields_. – pirho Oct 30 '17 at 18:53

1 Answers1

1

If your listeners have a lot of code in their 'listener' methods and you only need to change to which fields they have access (read/write), you could do something like the following.

First, an interface that represents a readable/writable thing:

public interface Model<T> {
    T getFieldValue();
    void setFieldValue(T value);
}

Then the listener using that thing:

public class TheListener<T> ... {
    private final Model<T> model;

    public TheListener(Model<T> model) {
        this.model = model;
    }

    public void onClick(...) {
        ...
        // read access
        model.getFieldValue();
        ...
        // write access
        model.setFieldValue(v);
        ...
    }
}

And then use it:

new TheListener<String>(new Model<String>() {
    public String getFieldValue() {
        return field1;
    }
    public void setFieldValue(String v) {
        field1 = v;
    }
});

new TheListener<String>(new Model<String>() {
    public String getFieldValue() {
        return field2;
    }
    public void setFieldValue(String v) {
        field2 = v;
    }
});

and so on.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72