美文网首页
浮窗WindowManager addView响应返回按键

浮窗WindowManager addView响应返回按键

作者: 小二小二小二 | 来源:发表于2020-06-22 21:08 被阅读0次

    显示悬浮框,注意一定不要设置WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,拿不到Focus是接收不到back事件的。

    private void showPreviewDialog(){
        View mPreviewLayout = LayoutInflater.from(getContext()).inflate(R.layout.window_preview,null);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
                /*WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE*/0,
                PixelFormat.TRANSLUCENT);
        mPreviewLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Logger.d(TAG,"onKey#keyCode="+keyCode+",event.getKeyCode()="+event.getKeyCode()+",event.getAction()="+event.getAction());
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                   //do sth.
                }
                return false;
            }
        });
        mWindowManager.addView(mPreviewLayout,layoutParams);
    }
    

    window_preview.xml文件:

    <?xml version="1.0" encoding="utf-8"?>
    <com.sunny.widget.BwRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <!--省略其它代码 -->
    
    </com.sunny.widget.BwRelativeLayout>
    

    BwRelativeLayout:

    package com.sunny.widget;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.KeyEvent;
    import android.widget.RelativeLayout;
    
    public class BwRelativeLayout extends RelativeLayout {
        public BwRelativeLayout(Context context) {
            super(context);
        }
    
        public BwRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public BwRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
                if(mOnKeyListener != null){
                    return mOnKeyListener.onKey(this,event.getKeyCode(),event);
                }
            }
            return super.dispatchKeyEvent(event);
        }
    
        OnKeyListener mOnKeyListener = null;
    
        @Override
        public void setOnKeyListener(OnKeyListener onKeyListener) {
            this.mOnKeyListener = onKeyListener;
            super.setOnKeyListener(onKeyListener);
        }
    }
    

    相关文章

      网友评论

          本文标题:浮窗WindowManager addView响应返回按键

          本文链接:https://www.haomeiwen.com/subject/znrkfktx.html