android叠加活动问题

时间:2014-12-22 22:11:24

标签: android touch overlay

我有一个活动创建了TYPE_SYSTEM_ALERT类型的视图,并为视图设置了一个触摸监听器。是否可以录制触摸但仍然将触摸事件发送到其他视图(例如:从我的主屏幕到小部件)?

这是我的代码:

public class TestGestures extends Activity implements View.OnTouchListener {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final WindowManager.LayoutParams param=new WindowManager.LayoutParams();
        param.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        final View view=findViewById(R.id.view1);
        final ViewGroup parent=(ViewGroup)view.getParent();
        if(parent!=null)
            parent.removeView(view);
        param.format= PixelFormat.RGBA_8888;
        param.type=WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        param.gravity= Gravity.TOP|Gravity.LEFT;
        param.width=view.getLayoutParams().width;
        param.height=view.getLayoutParams().height;
        //view.setBackgroundColor(android.R.color.white);
        final WindowManager wmgr=(WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        wmgr.addView(view,param);
        view.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }
}

当我在主屏幕时,触摸事件不会发送到小部件

1 个答案:

答案 0 :(得分:0)

您必须使用您用于设置WindowManager.LayoutParams的参数。例如,下面的代码将触摸事件传递到您刚创建的视图下方的活动(或视图):

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

另一方面,如果您将TYPE_SYSTEM_OVERLAY更改为TYPE_SYSTEM_PHONE,则输入事件将传递到位于其他视图之上的视图:

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

因此,在您的情况下,由于您希望将输入事件传递到下面的视图,请尝试设置TYPE_SYSTEM_OVERLAY标记。