浮窗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文件:

<?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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值