浮窗WindowManager addView响应返回按键

显示悬浮框,注意一定不要设置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文件:



    


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);
    }
}

你可能感兴趣的:(Android开发)