I was wondering if it is a good practice to use anonymous listeners?
For example I have a list of 50 items. Each of them has a onClickListener which is implemented using anonymous listener. Does that mean that I create 50 new items in to heap?
for (x;x;x) {
item.setOnClickListener(new OnClikListener() {
...
});
}
And if I just create 1 listener object and then assign those 50 list items to that single listener. Will it be more efficient?
OnClickListener listener = new OnClickListener() {
...
};
for (x;x;x) {
item.setOnClickListener(listener);
}
The fact that it’s anonymous is irrelevant. Every object instance you create goes on the heap. If you can reuse the same listener for many buttons, then definitely do it: it will need less memory, and will generate less garbage.