Reputation: 517
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?
Upvotes: 1
Views: 64
Reputation: 11835
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.
Upvotes: 1