1. 程式人生 > >[轉]懸浮控制元件的實現

[轉]懸浮控制元件的實現

public void showAddressTip(String number) {

   // TN的構造方法(參考Toast的原始碼)
      final LayoutParams params = new WindowManager.LayoutParams();
      // 設定寬高為WrapContent
      params.height = WindowManager.LayoutParams.WRAP_CONTENT;
      params.width = WindowManager.LayoutParams.WRAP_CONTENT;
      // 半透明
      params
.format = PixelFormat.TRANSLUCENT; // 型別為Toast // TYPE_PRIORITY_PHONE 優先於通話介面許可權:android.permission.SYSTEM_ALERT_WINDOW // Android保護機制: 在通話的時候,通話介面優先順序最高其他介面都不可被觸控 params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE; params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持螢幕常量
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 不可獲取焦點 // 焦點和觸控事件沒有任何關係 // |WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; //客官不可摸 // 載入佈局 final TextView tvAddress = (TextView) View.inflate(MyServicer.this, R.layout.tip_address, null
); // 設定內容 tvAddress.setText(number); tvAddress.setBackgroundResource(android.R.color.holo_green_light); // 獲取WindowManager final WindowManager mWm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); // 通過WindowManager新增一個控制元件最終控制元件會顯示在Window上 mWm.addView(tvAddress, params); tvAddress.setOnTouchListener(new OnTouchListener() { private int downX; private int downY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i("test", "down"); // 獲取當前點選下去的位置 downX = (int) event.getRawX(); downY = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE: Log.i("test", "move"); // 獲取X和Y的偏移量 int moveX = (int) event.getRawX(); int moveY = (int) event.getRawY(); // 計算差值 int dx = moveX - downX; int dy = moveY - downY; // 在原來的基礎上加上現在移動的差值 params.x = params.x + dx; params.y = params.y + dy; // 更新控制元件引數佈局 mWm.updateViewLayout(tvAddress, params); downX = moveX; downY = moveY; break; case MotionEvent.ACTION_UP: Log.i("test", "up"); break; default: break; } return false; } }); }