- Hands-On Android UI Development
- Jason Morris
- 286字
- 2021-07-02 23:26:10
Multiple event listeners
Unlike many other event systems, however, many Android components only allow a single event listener of certain types; this perges from platforms such as Java desktop, or JavaScript in the browser, where any number of click listeners can be attached to a single element. In Android, click listeners are almost always set rather than added.
This is actually a clever tradeoff--having multiple listeners for each event means that you need at least an array of them; the array needs to be sized and copied when it runs out of space, while it's actually very seldom that multiple listeners are needed. Multiple listeners also means that the widgets must traverse the list every time they want to dispatch events, so sticking to a single listener simplifies the code, and reduces the amount of required memory.
If you ever find yourself needing more than one listener for an event and widget that only provides a single listener slot, simply write a simple delegate class, like this:
public class MultiOnClickListener implements View.OnClickListener {
private final List<View.OnClickListener> listeners =
new CopyOnWriteArrayList<>();
public MultiOnClickListener(
final View.OnClickListener... listeners) {
this.listeners.addAll(Arrays.asList(listeners));
}
@Override
public void onClick(View v) {
for (final View.OnClickListener listener : listeners)
listener.onClick(v);
}
public void addOnClickListener(
final View.OnClickListener listener) {
if (listener == null) return;
listeners.add(listener);
}
public void removeOnClickListener(
final View.OnClickListener listener) {
if (listener == null) return;
listeners.remove(listener);
}
}
The preceding pattern allows compact and flexible multilistener delegation in the cases where you might need it. The CopyOnWriteArrayList class is an ideal listener container, as its internal array is only ever as large as the number of elements, so it remains compact (rather than having a buffer space like ArrayList and similar implementations).
- Game Programming Using Qt Beginner's Guide
- PHP 從入門(mén)到項(xiàng)目實(shí)踐(超值版)
- 實(shí)戰(zhàn)Java程序設(shè)計(jì)
- Elastic Stack應(yīng)用寶典
- Python程序設(shè)計(jì)
- Python Data Analysis Cookbook
- Julia高性能科學(xué)計(jì)算(第2版)
- Python算法指南:程序員經(jīng)典算法分析與實(shí)現(xiàn)
- Go語(yǔ)言精進(jìn)之路:從新手到高手的編程思想、方法和技巧(2)
- Java Web開(kāi)發(fā)實(shí)例大全(基礎(chǔ)卷) (軟件工程師開(kāi)發(fā)大系)
- 從Power BI到Analysis Services:企業(yè)級(jí)數(shù)據(jù)分析實(shí)戰(zhàn)
- 軟件工程與UML案例解析(第三版)
- Ext JS 4 Plugin and Extension Development
- INSTANT Apache ServiceMix How-to
- Building Microservices with Go