浮窗WindowManager view返回和Home按鍵事件監聽

出於功能需求,須要在全部的view之上顯示浮窗,因而須要在WindowManager的View上處理返回鍵的響應,android

mFloatingWindowView =  layoutInflater.inflate(R.layout.floating_window, null, false);


mFloatingWindowLayoutParams = new WindowManager.LayoutParams();
  // 設置window type
mUserConversationWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

mUserConversationWindowParams.format = PixelFormat.TRANSLUCENT;// 設置圖片格式,效果爲背景透明

// 設置Window flag
mUserConversationWindowParams.flags =
//可以使用FLAG_DISMISS_KEYGUARD選項直接解除非加鎖的鎖屏狀態。此選項只用於最頂層的全屏幕窗口。
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD

| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL //必須 設置窗口不攔截窗口範圍以外事件

|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH // 必須 設置在有FLAG_NOT_TOUCH_MODAL屬性時,窗口以外事件發生時本身也獲取事件

| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
mWindowManager.addView(mFloatingWindowView, mFloatingWindowLayoutParams);

這裏千萬要注意不能用WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,我就是死在這上面的,若是設置成FLAG_NOT_FOCUSABLE,死都收不到返回鍵的事件的!web

 

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.LinearLayout;

/**
 * Created by KB-Shirlman on 4/26/2016.
 */
public class FloatingWindowView extends LinearLayout {
    public FloatingWindowView(Context context) {
        super(context);
    }

    public FloatingWindowView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FloatingWindowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                || event.getKeyCode() == KeyEvent.KEYCODE_SETTINGS) {
if(event.getAction()==KeyEvent.ACTION_DOWN){ //按鍵 按下和移開會有兩個不一樣的事件因此須要區分
closecao(); //點擊返回 要執行的方法
}
} return super.dispatchKeyEvent(event); }  }

 

floating_window.xmlide

下面附贈哪都能搜索的到的WidnowManager Home按鍵監聽。this

打開浮窗時調用:spa

關閉浮窗時調用:code

相關文章
相關標籤/搜索