26
2017
09

windowManager使用

在桌面添加一个控件,并动态拖动它

代码实例

WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE );
       Button mFloatingButton = new Button(this );
         mFloatingButton .setText("windowManager" );
       LayoutParams mLayoutParams = new WindowManager.LayoutParams(
               LayoutParams. WRAP_CONTENT , LayoutParams.WRAP_CONTENT , 0, 0,
               PixelFormat. TRANSPARENT );
        mLayoutParams .flags = LayoutParams.FLAG_NOT_TOUCH_MODAL  //表示系统会将当前window区域以外的单机事件传递给底层window,当前window区域以内的单击事件则自己处理。这个标记一般需要开启,不然其他window将无法收到单击事件。
               | LayoutParams.FLAG_NOT_FOCUSABLE   //表示widnow不需要获取焦点
               | LayoutParams.FLAG_SHOW_WHEN_LOCKED ;  //让window显示在锁屏的界面上

        mLayoutParams .gravity = Gravity. LEFT | Gravity.TOP ;
        mLayoutParams .x = 100;  //屏幕x轴的100
        mLayoutParams .y = 300;  //屏幕y轴的300
          //将button添加到window上
            mWindowManager .addView(mFloatingButton , mLayoutParams);

           //将button移除
           // mWindowManager .removeView(mFloatingButton);

 //监听触摸滑动
mFloatingButton .setOnTouchListener( new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event ) {
                   int rawX = ( int) event .getRawX();
                   int rawY = ( int) event .getRawY();

                   switch (event .getAction()) {
                   case MotionEvent.ACTION_MOVE :
                       mLayoutParams .x = rawX -100;
                       mLayoutParams .y = rawY -100;
                       mWindowManager .updateViewLayout(mFloatingButton , mLayoutParams );
                       break ;

                   default :
                       break ;
                  }
                return false ;
           }
       });

上一篇:popwindow弹出后点击外部控件响应点击事件 下一篇:Android性能优化--Inspact Code代码检查