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


出於功能需求,需要在所有的view之上顯示浮窗,於是需要在WindowManager的View上處理返回鍵的響應,

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,死都收不到返回鍵的事件的!

 

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.xml

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

打開浮窗時調用:

關閉浮窗時調用:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM