2.原理
Window我们应该很熟悉,它是一个接口类,具体的实现类为PhoneWindow,它可以对View进行管理。WindowManager是一个接口类,继承自ViewManager,从名称就知道它是用来管理Window的,它的实现类是WindowManagerImpl。如果我们想要对Window(View)进行添加、更新和删除操作就可以使用WindowManager,WindowManager会将具体的工作交由WindowManagerService处理。这里我们只需要知道WindowManager能用来管理Window就好。
WindowManager是一个接口类,继承自ViewManager,ViewManager中定义了3个方法,分布用来添加、更新和删除View,如下所示:
public interface ViewManager {
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
WindowManager也继承了这些方法,而这些方法传入的参数都是View类型,说明了Window是以View的形式存在的。
3.具体实现
3.1浮窗布局
悬浮窗的简易布局如下的可参考下面的layout_floating_window.xml文件。顶层深色部分的FrameLayout布局是用来实现悬浮窗的拖拽功能的,点击右上角ImageView可以实现关闭悬浮窗,剩下区域显示内容,这里只是简单地显示文本内容,不做复杂的东西,故只设置TextView。
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”>
<FrameLayout
android:id=“@+id/layout_drag”
android:layout_width=“match_parent”
android:layout_height=“15dp”
android:background=“#dddddd”>
<androidx.appcompat.widget.AppCompatImageView
android:id=“@+id/iv_close”
android:layout_width=“15dp”
android:layout_height=“15dp”
and

本文介绍了Android悬浮窗的实现原理和步骤,包括使用`ViewManager`接口管理View,通过`WindowManager`添加、更新和删除悬浮窗。详细讲解了创建浮窗布局、使用服务保持后台显示、实现拖拽和关闭功能,以及设置必要的权限。还提供了拖动悬浮窗的触控事件处理和广播通信的实现方法。
最低0.47元/天 解锁文章
3535

被折叠的 条评论
为什么被折叠?



