关闭

通过WindowManager实现拖动悬浮框

100人阅读 评论(0) 收藏 举报

   最近在弄一个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;
	}

}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1450次
    • 积分:60
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条