Android添加可拖动、点击的悬浮窗口

原文地址:http://mobile.9sssd.com/android/art/1288,貌似这个地址也不是原创不过我是看的这个。。就这个吧。。。这个例子蛮不错,简单易懂,注释也很全,只是运行之后发现有个小bug,往左上角拖动的时候会执行点击事件,造成的原因也很简单,就是判断移动X、Y的时候相减的那个值为负数造成的,取下绝对值就好了,在下面的代码中已经修改。

以下是原文:

实现这种功能,主要有两步:

1.判断当前显示的是为桌面。这个内容我在前面的帖子里面已经有过介绍,如果还没看过的赶快稳步看一下哦。

2.使用windowManager往最顶层添加一个View 

这个知识点就是为本文主要讲解的内容哦。在本文的讲解中,我们还会讲到下面的知识点:

a.如果获取到状态栏的高度

b.悬浮窗口的拖动

c.悬浮窗口的点击事件

在开始之前,我们先来看一下效果图:

Android在桌面添加可拖动、点击的悬浮窗口



首先FloatView的代码FloatView是一个自定义的可拖动控件。

部分代码解释:

1、int statusBarHeight = frame.top; 

为获取状态栏的高度,为什么在event.getRawY()的时候减去状态栏的高度呢?

因为我们的悬浮窗口不可能显示到状态栏中去,而后getRawY为获取到屏幕原点的距离。当我们屏幕处于全屏模式时,获取到的状态栏高度会变成0 。

2、(x - mStartX) < 5 && (y - mStartY) < 5

如果我们在触摸过程中,移动距离少于5 ,则视为点击,触发点击的回调。

(这个就是bug的地方,改成  Math.abs(x - mStartX) < 5 && Math.abs(y - mStartY) < 5  即可)

<span style="font-family:Comic Sans MS;font-size:18px;">public class FloatView extends ImageView {
	private float mTouchX;
	private float mTouchY;
	private float x;
	private float y;
	private float mStartX;
	private float mStartY;
	private OnClickListener mClickListener;
	private WindowManager windowManager;
	// 此windowManagerParams变量为获取的全局变量,用以保存悬浮窗口的属性
	private WindowManager.LayoutParams windowManagerParams;

	public FloatView(Context context) {
		super(context);
		windowManager = (WindowManager) getContext()
				.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
		windowManagerParams = ((MyApplication) getContext()
				.getApplicationContext()).getWindowParams();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// 获取到状态栏的高度
		Rect frame = new Rect();
		getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		// 获取相对屏幕的坐标,即以屏幕左上角为原点
		x = event.getRawX();
		y = event.getRawY() - statusBarHeight; // statusBarHeight是系统状态栏的高度
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: // 捕获手指触摸按下动作
			// 获取相对View的坐标,即以此View左上角为原点
			mTouchX = event.getX();
			mTouchY = event.getY();
			mStartX = x;
			mStartY = y;
			break;
		case MotionEvent.ACTION_MOVE: // 捕获手指触摸移动动作
			updateViewPosition();
			break;
		case MotionEvent.ACTION_UP: // 捕获手指触摸离开动作
			updateViewPosition();
			mTouchX = mTouchY = 0;
			//取绝对值
			if (Math.abs(x - mStartX) < 5 && Math.abs(y - mStartY) < 5) {
				if (mClickListener != null) {
					mClickListener.onClick(this);
				}
			}
			break;
		}
		return true;
	}

	@Override
	public void setOnClickListener(OnClickListener l) {
		this.mClickListener = l;
	}

	private void updateViewPosition() {
		// 更新浮动窗口位置参数
		windowManagerParams.x = (int) (x - mTouchX);
		windowManagerParams.y = (int) (y - mTouchY);
		windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
	}
}</span>



然后我们需要 另外我们需要自定义一个application

自定义application的目的是为了保存windowParams的值 ,因为我们在拖动悬浮窗口的时候,如果每次都重新new一个layoutParams的话,在update的时候会在异常发现。

windowParams的值也不一定非得在自定义application里面来保存,只要是全局的都行。

<span style="font-family:Comic Sans MS;font-size:18px;">public class FloatApplication extends Application {
	private WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();

	public WindowManager.LayoutParams getWindowParams() {
		return windowParams;
	}
}</span>


最后我们再来看看Activity中的实现

在activity中我们主要是添加悬浮窗,并且设置他的位置。另外需要注意flags的应用:

<span style="font-family:Microsoft YaHei;">LayoutParams.FLAG_NOT_TOUCH_MODAL 不影响后面的事件
    LayoutParams.FLAG_NOT_FOCUSABLE  不可聚焦
    LayoutParams.FLAG_NOT_TOUCHABLE 不可触摸</span>
    最后我们在onDestroy()中移除到悬浮窗口。所以,我们测试的时候,记得按Home键来切换到桌面。

<span style="font-family:Comic Sans MS;font-size:18px;">public class MainActivity extends Activity implements OnClickListener {
	private WindowManager windowManager = null;
	private FloatView floatView = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 取消标题栏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏
		setContentView(R.layout.activity_main);
		createView();
	}

	public void onDestroy() {
		super.onDestroy();
		// 在程序退出(Activity销毁)时销毁悬浮窗口
		windowManager.removeView(floatView);
	}

	private void createView() {
		floatView = new FloatView(getApplicationContext());
		floatView.setOnClickListener(this);
		floatView.setImageResource(R.drawable.ic_launcher); // 这里简单的用自带的icon来做演示
		// 获取WindowManager
		windowManager = (WindowManager) getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);
		// 设置LayoutParams(全局变量)相关参数
		LayoutParams windowManagerParams = ((FloatApplication) getApplication())
				.getWindowParams();
		windowManagerParams.type = LayoutParams.TYPE_PHONE; // 设置window type
		windowManagerParams.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明
		// 设置Window flag
		windowManagerParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_NOT_FOCUSABLE;
		/*
		 * 注意,flag的值可以为: LayoutParams.FLAG_NOT_TOUCH_MODAL 不影响后面的事件
		 * LayoutParams.FLAG_NOT_FOCUSABLE 不可聚焦 LayoutParams.FLAG_NOT_TOUCHABLE
		 * 不可触摸
		 */
		// 调整悬浮窗口至左上角,便于调整坐标
		windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP;
		// 以屏幕左上角为原点,设置x、y初始值
		windowManagerParams.x = 0;
		windowManagerParams.y = 0;
		// 设置悬浮窗口长宽数据
		windowManagerParams.width = LayoutParams.WRAP_CONTENT;
		windowManagerParams.height = LayoutParams.WRAP_CONTENT;
		// 显示myFloatView图像
		windowManager.addView(floatView, windowManagerParams);
	}

	public void onClick(View v) {
		Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
	}
}</span>


最后千万记得,在androidManifest.xml中来申明我们需要用到的ndroid.permission.SYSTEM_ALERT_WINDOW权限,并且记得申明我们自定义的application哦。

AndroidManifest.xml代码如下

<span style="font-family:Comic Sans MS;font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testwindow"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:name="com.example.testwindow.FloatApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testwindow.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest></span>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值