今天我要讲的是如何用WindowManager去实现一个悬浮窗迷你音乐盒。,由于WindowManager这一块内容会比较多,所以我决定分成上下两篇来写这一块,这一篇主要介绍WindowManager和它的一些属性,可能会有些枯燥,下一篇我会具体去写悬浮迷你音乐盒的实现。
WindowManager在Android应用开发中,其实整个Android的窗口机制是基于一个叫做WindowManager的一个系统服务接口,WindowManager可以添加view到屏幕,也可以从屏幕删除view。它面向的对象一端是屏幕,另一端就是View,其实就连我们常用的Activity和Diolog的底层实现都是通过WindowManager, WindowManager是全局的,整个系统就只用一个Windowmanager服务,我们需要向系统获取服务才能调用它,而它就是显示View的最底层。
其实WindowManager用起来非常方便,就三个方法:
添加ViewaddView(View view, WindowManager.LayoutParams params);
从方法中我们可以看到,addView需要两个参数,view简单,就是我们要向窗口中去添加的对象,至于params,就是给窗口设置的显示策略,包括窗口的大小、透明度等等,这个也是今天文章的重点,在后文会有所介绍。
移除ViewremoveView(View view);
既然能够向窗口去添加View,当然也就能够从窗口上移除View,这个很简单view就是你要从窗口中移除的对象。
刷新ViewupdateViewLayout(View view, ViewGroup.LayoutParams params)
同样窗口刷新也需要两个参数,和添加View一样view是需要更新的对象,而params就是更新后的策略属性。
WindowManager.LayoutParams相比于WindowManager,WindowManager.LayoutParams可就要复杂好多了。WindowManager.LayoutParams是 WindowManager 接口的嵌套类,在窗口管理中扮演着重要的角色。它继承于ViewGroup.LayoutParams,它用于向WindowManager描述窗口的管理策略;WindowManager.LayoutParams可以直接new WindowManager.LayoutParams()新建,也可以从对窗口的getAttributes()得到其WindowManager.LayoutParams对象。WindowManager.LayoutParams常用的有以下主要常量成员:
flag以上的也是最常用到的几个flag属性了吧,其他还有很多,也希望大家空闲之余能够去研究研究,欢迎再评论区补充。
typetype主要用于表示window的类型。我们可以通过WindowManager.LayoutParams的type变量对窗口类型直接进行设置。常用的窗口类型也就以下两种:
其中screenBrightness表示屏幕的亮度,而buttonBrightness表示一般按键和键盘按键的亮度。它们都拥有以下三个系统属性:
讲flag属性的时候有提到过,这个参数是要和WindowManager.LayoutParams.FLAG_DIM_BEHIND这个flag属性一起使用,dimAmount的取值在0.0f~1.0f之间,取值越大背景的变暗程度越高,默认取值1.0f。
width、height这里的width、height其实和View中的width、height一样的理解,就是控制窗口视图的大小,可以具体取值,也可以使用系统属性:
窗口的对齐方式,一般在创建窗口的时候,都会设置gravity为左上角对齐,也就是Gravity.LEFT | Gravity.TOP,因为窗口的坐标设置,是基于gravity来进行计算的,设置gravity左上角,刚好是和系统的坐标相对应,方便计算。
x、y
x和y用于控制窗口的坐标位置,如果有设置gravity的话,x和y设置的就是在gravity这个基础上的一个偏移量。不设置gravity的话,x和y就是一个绝对坐标。因此,将gravity设置为Gravity.LEFT | Gravity.TOP是最易于开发的。需要注意的一点是:设置y的时候常常需要考虑状态栏的高度。
正常情况下,就算x和y的坐标已经在设备之外,也会贴边显示。而如果设置属性FLAG_LAYOUT_NO_LIMITS则相对于系统的坐标如果x和y超出设备,那么超出部分将无法显示。
windowAnimations控制的是窗口出现和消失的动画效果,设置的是要系统自带的动画效果(android.R.style之下的动画效果),因为窗口管理器是不能访问应用资源的。
formatformat可以理解为最后窗口生成的位图是什么格式,默认背景是黑色的。一般我们都设置为PixelFormat.RGBA_8888,这样我们的窗口就会有一个透明的背景。
alpha这个不难理解,设置窗口的透明度。
怎么样,是否打动你继续往下看呢?
如果对WindowManager没有接触过得小伙伴,建议先看我的上一篇文章,因为,两篇连着一起看才好看哦。其实实现这么一个悬浮迷你音乐盒的功能也并不难,首先需要两个布局,一个就是像效果图中展示的可以四处拖动的View的布局我们暂且称它为floatView,它的实现很简单其实就是我之前讲过的用RotateDrawable实现网易云音乐唱片机效果的迷你版。另一个就是点击floatView后跳出的歌曲控制菜单的布局,我们可以叫它playerView。
floatView.xml<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent" > <RelativeLayout android:background="@drawable/shape_background_light" android:layout_centerInParent="true" android:layout_height="52dp" android:layout_width="52dp" > <ImageView android:id="@+id/mini_cd" android:src="@drawable/rotate_cd" android:layout_width="match_parent" android:layout_height="match_parent" /> <ImageView android:id="@+id/mini_hander" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/rotate_hander" /> </RelativeLayout> </RelativeLayout>playerView.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:layout_width="match_parent" > <LinearLayout android:background="@drawable/shape_background_dark" android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="vertical" android:paddingRight="12dp" android:paddingLeft="12dp" android:paddingTop="8dp" android:gravity="center" > <TextView android:layout_height="wrap_content" android:id="@+id/player_displayname" android:focusableInTouchMode="true" android:ellipsize="marquee" android:layout_width="180dp" android:textColor="#11CD6E" android:singleLine="true" android:focusable="true" tools:text="浅唱 - 许嵩" android:gravity="center" android:textSize="18sp" android:text="N/A" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/player_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="8dp" android:layout_marginTop="3dp" tools:text="04:15" android:text="--:--" android:textColor="#11CD6E" android:textSize="8sp" /> <TextView android:id="@+id/player_duration" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" android:layout_alignParentRight="true" android:textColor="#11CD6E" android:layout_marginTop="3dp" android:text="--:--" tools:text="12:45" android:textSize="8sp" /> </RelativeLayout> <SeekBar android:id="@+id/player_seek" tools:progress="50" android:progress="0" android:max="100" tools:secondaryProgress="90" android:paddingBottom="3dp" android:progressDrawable="@drawable/layer_seekbar" android:thumb="@drawable/shape_thumb" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="1" android:minHeight="2dp" android:maxHeight="2dp" /> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" android:padding="6dp" > <ImageButton android:background="@null" android:layout_width="36dp" android:layout_height="36dp" android:id="@+id/player_previous" android:src="@mipmap/landscape_player_btn_pre_press" /> <ImageButton android:background="@null" android:layout_width="48dp" android:layout_height="48dp" android:id="@+id/player_play" android:layout_marginLeft="18dp" android:layout_marginRight="18dp" android:src="@mipmap/landscape_player_btn_play_press" /> <ImageButton android:background="@null" android:layout_width="36dp" android:layout_height="36dp" android:id="@+id/player_next" android:src="@mipmap/landscape_player_btn_next_press" /> </LinearLayout> </LinearLayout> </RelativeLayout>
布局写好,接着就是写一个类来控制这两个View之间的转换以及一些属性的设置,代码确实有点,全贴出来的话,相信不少人都会看厌、看烦,我还是选择其中比较有代表性的代码,再进行一番说明,可能更有助于大家理解我写这个Demo时思考的角度,老规矩在文章末尾我会附上源码下载地址,有兴趣的小伙伴可以下载研究。
floatView的设置public void setFloatView(View floatView) { if(floatView != null) { this.mFloatView = floatView; setContentView(mFloatView); } }
首先,floatView的设置非常简单。至于setContentView(mFloatView),是因为悬浮窗默认首先显示的是小窗口,所以在设置MenuView的时候,就将窗口的布局设置为floatView。
playerView的设置public void setPlayerView(View PlayerView) { if(PlayerView != null) { BackgroundView backgroundView = new BackgroundView(getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); PlayerView.setOnTouchListener(new TouchIntercept()); PlayerView.setLayoutParams(layoutParams); backgroundView.addView(PlayerView); this.mPlayerView = backgroundView; } }
menuView的设置相对于floatView的设置复杂一些,大家可以看到,我为添加进来的MenuView包裹了一层BackgroundView,而这一点正是从PopupWindow的源码中借鉴而来,BackgroundView是一个自定义内部类,继承至RelativeLayout,并且重写按键点击监听事件和触摸事件,主要是用于PlayerView的返回键关闭功能和外部点击关闭功能。
内部类BackgroundViewclass BackgroundView extends RelativeLayout { public BackgroundView(Context context) { super(context); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (getKeyDispatcherState() == null) { return super.dispatchKeyEvent(event); } if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { final KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { final KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null && state.isTracking(event) && !event.isCanceled()) { closeMenu(); return true; } } return super.dispatchKeyEvent(event); } else { return super.dispatchKeyEvent(event); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: closeMenu(); return true; case MotionEvent.ACTION_OUTSIDE: closeMenu(); return true; } return super.onTouchEvent(event); } }ContentView的初始化准备
private void createContentView(View contentView) { this.mContentView = contentView; contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); // 主动计算视图View的宽高信息 offsetY = getStatusBarHeight(getContext()) + contentView.getMeasuredHeight() / 2; offsetX = contentView.getMeasuredWidth() / 2; contentView.setOnTouchListener(new WindowTouchListener()); }
由于我们要实现的悬浮迷你音乐盒,是需要在两个视图之间进行切换的,所以在每次视图切换之前,我都会对先要加载的视图进行一个准备,由代码contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)可以看到,主动计算出当前View的宽高信息,还有就是getStatusBarHeight(getContext())计算设备状态栏高度的方法,因为在窗口移动的时候,默认x、y指定的是窗口左上角的坐标,这样就涉及到一个偏移量的问题,在排除偏移量问题后,我们的坐标就会精确指定窗口的正中心。而且在代码中能够明显看出,我对contentView设置了一个onTouch触摸事件,主要是实现窗口的滑动,具体实现在后面会有介绍。
WindowManager.LayoutParams初始化配置private void initLayoutParams() { getLayoutParams().flags = getLayoutParams().flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; getLayoutParams().dimAmount = 0.2f; getLayoutParams().type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; getLayoutParams().height = WindowManager.LayoutParams.WRAP_CONTENT; getLayoutParams().width = WindowManager.LayoutParams.WRAP_CONTENT; getLayoutParams().gravity = Gravity.LEFT | Gravity.TOP; getLayoutParams().format = PixelFormat.RGBA_8888; getLayoutParams().alpha = 1.0f; offsetX = 0; offsetY = getStatusBarHeight(getContext()); getLayoutParams().x = (int) (mDisplayMetrics.widthPixels - offsetX); getLayoutParams().y = (int) (mDisplayMetrics.heightPixels * 1 / 4 - offsetY); }
由上篇文章介绍,WindowManager.LayoutParams控制着窗口显示的策略,因此在窗口显示之前,我们要完成对WindowManager.LayoutParams的配置。由上面的代码看出,窗口类型是系统提示窗口,也就上篇文章中说到的可以显示在任何视图之上的那种窗口类型,窗口的宽高是自适应。对齐方式是左上角对齐。窗口的透明度为1.0,也就是不透明。虽然窗口并没有设置属性FLAG_NOT_FOCUSABLE,也就是说我们的窗口默认是设置焦点的,但是由于我设置FLAG_WATCH_OUTSIDE_TOUCH属性的缘故,窗口外的区域,还是能够自由接收点击触摸事件的。
视图切换private void setContentView(View contentView) { if(contentView != null) { if(isShowing()) { getWindowManager().removeView(mContentView); createContentView(contentView); getWindowManager().addView(mContentView, getLayoutParams()); updateLocation(getDisplayMetrics().widthPixels / 2, getDisplayMetrics().heightPixels / 2 ,true); } else { createContentView(contentView); } } }
从代码中可以看出,视图切换用到的上篇文章中介绍到的视图的移除和视图的添加,是的,想要进行视图新的切换,首先要移除原有的视图,并将需要显示的视图添加进来。
窗口位置更新private void updateLocation(float x, float y, boolean offset) { if(getContentView() != null) { if(offset) { getLayoutParams().x = (int) (x - offsetX); getLayoutParams().y = (int) (y - offsetY); } else { getLayoutParams().x = (int) x; getLayoutParams().y = (int) y; } getWindowManager().updateViewLayout(mContentView, getLayoutParams()); } }
在视图切换中用到了窗口的移除和窗口的添加,而在位置更新中用到的是WindowManger三个方法中的第三个方法窗口更新,通过传入我们需要重新设置WindowManager.LayoutParams中的x、y位置坐标,然后更新窗口,就能实现窗口位置的更新操作。
contentView的触摸事件private final float DISTANCE = 15.0f; class WindowTouchListener implements View.OnTouchListener { @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if(!isOpen) { down(event); } break; case MotionEvent.ACTION_MOVE: if(!isOpen) { move(event); } break; case MotionEvent.ACTION_UP: if(!isOpen) { up(event); } break; case MotionEvent.ACTION_OUTSIDE: if(isOpen) { closeMenu(); return true; } break; default: break; } return false; } } /** * 按下事件处理 * */ private void down(MotionEvent event) { downX = event.getRawX(); downY = event.getRawY(); } /** * 移动事件处理 * */ private void move(MotionEvent event) { updateLocation(event.getRawX(), event.getRawY(), true); } /** * 抬起事件处理 * */ private void up(MotionEvent event) { float x = event.getRawX(); float y = event.getRawY(); if(x >= downX - DISTANCE && x <= downX + DISTANCE && y >= downY - DISTANCE && y <= downY + DISTANCE) { if(System.currentTimeMillis() - downTimeMillis > 1200) { // 长按 } else { openMenu(); //点击 } } else { ValueAnimator animator = alignAnimator(x, y); animator.start(); } }
floatView的触摸监听事件非常简单,就是根据手指触摸的坐标位置实时刷新窗口的坐标位置,当up坐标和dowm坐标的区域在预先设置好的合理范围内,触摸事件超过1秒钟则视为长按事件,小于1秒钟则视为点击事件,移除floatView,添加playerView。注意区别MotionEvent的getX、getY和getRawX、getRawY方法,getX、getY点击位置在视图内的坐标,getRawX、getRawY则是点击位置相对于整个屏幕的坐标
打开PlayerViewpublic void openMenu() { if(isOpen) { return ; } getLayoutParams().height = WindowManager.LayoutParams.MATCH_PARENT; getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT; oldX = getLayoutParams().x; oldY = getLayoutParams().y; setContentView(mPlayerView); isOpen = true; }
打开playerView后,我设置的的窗口大小是占满整个屏幕,这样就能完全捕捉到BackgroundView中设置的触摸事件,实现点击窗口外部关闭的效果。oldX、oldY则用于记录floatView移除前的坐标,方便在重新显示的时候定位。
关闭PlayerViewpublic void closeMenu() { if(!isOpen) { return ; } isOpen = false; getLayoutParams().height = WindowManager.LayoutParams.WRAP_CONTENT; getLayoutParams().width = WindowManager.LayoutParams.WRAP_CONTENT; setContentView(mFloatView); updateLocation(oldX, oldY, false); }
关闭PlayerView的方法也很简单,就是重新将试图切换为floatView,设置窗口大小为自适应大小,并定位在之前视图记录的原有坐标。
用WindowManager做一个炫酷的悬浮迷你音乐盒 转载https://www.codesocang.com/appboke/36794.html
热门源码