WindowManger


  1. create a windowmanger,which can receive key events,and do not prevent the events.

public class MainActivity extends AppCompatActivity

{

   private WindowManager mWindowManager;
   private WindowManager.LayoutParams mLParams;
   private ImageView mPopupView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       initWM();
       initPopupView();
   }

   @Override
   protected void onDestroy() {
       super.onDestroy();
       mWindowManager.removeView(mPopupView);
   }

   private void initWM()
   {
       mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
       mLParams = new WindowManager.LayoutParams(
               WindowManager.LayoutParams.WRAP_CONTENT, //w
               WindowManager.LayoutParams.WRAP_CONTENT, //h
               WindowManager.LayoutParams.TYPE_PHONE, //type,設置顯示的類型,TYPE_PHONE指的是來電話的時候會被覆蓋,其他時候會在最前端顯示

               WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON  //flag
                       | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                       | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, //不阻塞事件傳遞到後面的窗口
               PixelFormat.TRANSLUCENT // 不設置這個彈出框的透明遮罩顯示爲黑色
       );
       //設置對齊方式
       mLParams.gravity = Gravity.CENTER;
       //設置顯示的位置
       mLParams.x = 0;  //base on gravity
       mLParams.y = 0;
   }
   
   private void initPopupView()
   {
       mPopupView = new ImageView(this);
       mPopupView.setImageResource(R.mipmap.ic_launcher);
//        mPopupView.setFocusable(true);
       mPopupView.setFocusableInTouchMode(true);  //enable receive key events
       mPopupView.setOnKeyListener(new View.OnKeyListener() {
           @Override
           public boolean onKey(View view, int keyCode, KeyEvent event) {
               if (keyCode == KeyEvent.KEYCODE_BACK
                       && event.getRepeatCount() == 0
                       && event.getAction() == KeyEvent.ACTION_UP) {
                   Toast.makeText(MainActivity.this, "press back key", Toast.LENGTH_SHORT).show();
               } else if (keyCode == KeyEvent.KEYCODE_ENTER
                       && event.getRepeatCount() == 0
                       && event.getAction() == KeyEvent.ACTION_UP) {
                   Toast.makeText(MainActivity.this, "press enter key", Toast.LENGTH_SHORT).show();

               } else {
                   Toast.makeText(MainActivity.this, "press key:keyCode="+keyCode, Toast.LENGTH_SHORT).show();

               }
               return false;
           }
       });
   }

   private boolean mbVisible;

   public void onClick(View view) {
       if (mbVisible = !mbVisible) {
           mWindowManager.addView(mPopupView, mLParams);  //show View
       } else {
           mWindowManager.removeViewImmediate(mPopupView);  //remove View
       }
   }
   

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章