官术网_书友最值得收藏!

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).

主站蜘蛛池模板: 平湖市| 禄丰县| 信阳市| 施甸县| 天峻县| 静宁县| 昌宁县| 庆安县| 温泉县| 平舆县| 高青县| 天津市| 岚皋县| 开平市| 甘南县| 阳西县| 准格尔旗| 光泽县| 台山市| 康乐县| 神农架林区| 广昌县| 体育| 蒙城县| 临夏县| 青浦区| 都匀市| 河东区| 山西省| 鄂托克旗| 衢州市| 吉首市| 阿鲁科尔沁旗| 澄迈县| 革吉县| 泾川县| 榆林市| 尼勒克县| 廊坊市| 平定县| 威宁|