1. 程式人生 > >通過WindowManager實現拖動懸浮框

通過WindowManager實現拖動懸浮框

   最近在弄一個WindowManager拖動的小demo,重新研究了一下 WindowManager。

   直接上原始碼:

  

package com.haihang.floatviewdemo;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;

public class FloatView implements OnTouchListener {

	private Context mContext;
	private static WindowManager mWm;
	private static WindowManager.LayoutParams mWinParams;
	private static View view;
	private float mDownX;
	private float mDownY;
	private float mMoveX;
	private float mMoveY;

	public FloatView(Context context) {
		this.mContext = context;

		view = View.inflate(mContext, R.layout.float_view, null);

		mWm = (WindowManager) context.getApplicationContext().getSystemService(
				Context.WINDOW_SERVICE);

		mWinParams = new WindowManager.LayoutParams();
		mWinParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		mWinParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		mWinParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		mWinParams.format = PixelFormat.TRANSLUCENT;
		// mParams.windowAnimations =
		// com.android.internal.R.style.Animation_Toast;//動畫設定
		//在小米手機的 5.0系統中,需要設定 type為 TYPE_TOAST,才能顯示
		mWinParams.type = WindowManager.LayoutParams.TYPE_TOAST;

		view.setOnTouchListener(this);
	}

	public void show() {
		mWm.addView(view, mWinParams);
	}
	
	public void hide(){
		if(mWm != null){
			mWm.removeView(view);
		}
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			
			mDownX = event.getRawX();
			mDownY = event.getRawY();
			
			break;
		case MotionEvent.ACTION_MOVE:
			
			/**
			 * 最為關鍵的就是拖動業務的座標位置的計算
			 */
			
			mMoveX = event.getRawX();
			mMoveY = event.getRawY();

			float difX =  (mMoveX - mDownX);
			float difY =  (mMoveY - mDownY);
			
			mWinParams.x += difX;
			mWinParams.y += difY;
			
			mWm.updateViewLayout(view, mWinParams);
			
			mDownX = mMoveX;
			mDownY = mMoveY;
			
			break;
		case MotionEvent.ACTION_UP:

			break;

		default:
			break;
		}

		// 消費觸控事件
		return true;
	}

}