gpt4 book ai didi

java - 拦截点击/触摸事件而不重写 ViewGroup 或 View 方法

转载 作者:行者123 更新时间:2023-12-02 12:17:21 25 4
gpt4 key购买 nike

有什么办法可以拦截/装饰 View 的触摸事件而不扩展View或包装在一些ViewGroup(它可以拦截子事件)中?

假设我有 ExpandableListView 来处理项目点击事件。如果我在适配器 OnClickListenerOnTouchListener 中设置适配器返回的膨胀项目 View ,则 ExpandableListView 不会执行相应的操作(组展开),因为事件是由项目的监听器消耗。

我不想使用 ExpandableListView#setOnItemClickListener 的原因是,我想在适配器中装饰点击事件而不使用 ExpandableListView 依赖项。

最佳答案

我找到了解决这个问题的有效方法。

解决方案:在OnTouchListener中收集事件克隆,然后将它们分派(dispatch)到父 View 。

private final Queue<MotionEntry> consumedEvents = new LinkedList<>();
private final AtomicBoolean isDispatching = new AtomicBoolean(false);
...
groupView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
// we don't want to handle re-dispatched event...
if (isDispatching.get()) {
return false;
}
// create clone as event might be changed by parent
MotionEvent clone = MotionEvent.obtain(e);
MotionEntry entry = new MotionEntry(v, clone);
consumedEvents.add(entry);

// consume ACTION_DOWN in order to receive subsequent motion events
// like ACTION_MOVE, ACTION_CANCEL/ACTION_UP...
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
return true;
}
// we do not want to handle canceled motion...
if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
consumedEvents.clear();
return false;
}
// at this moment we have intercepted whole motion
// = re-dispatch to parent in order to apply default handling...
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
dispatchEvents();
}
return true;
}
});
...

发货方式:

private void dispatchEvents() {
isDispatching.set(true);
while (!consumedEvents.isEmpty()) {
MotionEntry entry = consumedEvents.poll();

ViewGroup parent = (ViewGroup) entry.view.getParent();
if (parent == null || entry.view.getVisibility() != View.VISIBLE) {
continue; // skip dispatching to detached/invisible view
}
// make position relative to parent...
entry.event.offsetLocation(entry.view.getLeft(), entry.view.getTop());
entry.event.setSource(PARENT_DISPATCHER);
parent.dispatchTouchEvent(entry.event);

if (event.getActionMasked() == MotionEvent.ACTION_UP) {
clickListener.onClick(entry.view);
}
}
isDispatching.set(false);
}

辅助类

private class MotionEntry {
private final View view;
private final MotionEvent event;

public MotionEntry(View view, MotionEvent event) {
this.view = view;
this.event = event;
}
}

关于java - 拦截点击/触摸事件而不重写 ViewGroup 或 View 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46056949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com