Android:将触摸事件委托给下层视图

22
我有以下的层级关系: Activity -> PopupWindow -> CustomView 我的PopupWindow本身是一个正方形,但是透明,所以可以看到后面的Activity。 CustomView是嵌入在PopupWindow中的一个圆。 alt text 目前我已经实现了:
  1. 用户点击绿色圆圈时,我会调用“一些内容”
  2. 用户点击PopupWindow外部,触摸事件将被派发给Activity。
现在缺少的部分是将发生在PopupWindow内但位于CustomView(圆形)之外的任何触摸事件派发给Activity。
我已经知道如何检测到触摸是否在我的圆圈之外。 我只是无法将其委托给Activity。
在我的CustomView中,我在onTouch方法中有以下代码:
if (radiusTouch > maxRadius) {
    return false;
}

在我的PopupWindow中,我已经设置了以下内容,但从未被调用:

popup.setTouchInterceptor(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i(TAG, "PopupWindow :: onTouch()");
        return false;
    }
});

我还需要做什么才能将触摸事件委托到活动(Activity)呢?


3
你是如何制作那个模型的?它看起来相当不错。 - browep
1
你是如何将点击事件分派到 PopUpWindow 下面的视图中的? - whlk
1
Mocups已经由Balsamic Mockups完成 http://balsamiq.com/products/mockups/ - Martin Frank
https://dev59.com/qGEh5IYBdhLWcg3w12il - Ayyappa
3个回答

13

考虑一下FLAG_NOT_TOUCH_MODAL:

/** Window flag: Even when this window is focusable (its
  * {@link #FLAG_NOT_FOCUSABLE is not set), allow any pointer events
  * outside of the window to be sent to the windows behind it.  Otherwise
  * it will consume all pointer events itself, regardless of whether they
  * are inside of the window. */
public static final int FLAG_NOT_TOUCH_MODAL    = 0x00000020;

您可以使用此代码在弹出窗口显示后更新窗口标志。

FrameLayout popupContainer = (FrameLayout)contentView.getParent();
WindowManager.LayoutParams p = (WindowManager.LayoutParams)popupContainer.getLayoutParams();
p.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
windowManager.updateViewLayout(popupContainer, p);

好的。它可以工作了。我可以在popupWindow和活动视图中都触摸到。只需使用updateViewLayout(contentView, p),不需要contentView.getParent() - Yeung

3

尝试在您的PopupWindow实例上设置以下内容:

window.setBackgroundDrawable(new BitmapDrawable());

window.setOutsideTouchable(true);

window.setTouchable(true);

这仅仅是一个建议......我没有测试过。

如果它起作用,请告诉我。

[注意:这是为了在触摸事件中调用onTouch()方法。]


0

很遗憾PopupWindow不是ViewGroup或者View的子类,否则你就可以重写dispatchTouchEvent方法了。你能修改你的自定义视图让它知道PopupWindow并在圆外部点击时调用dismiss()方法吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接