在工作中遇到开发悬浮窗的需求,在此整理一下,记录心得O(∩_∩)O哈哈~
大概的思路如下:
我们将悬浮窗绑定在一个service中,某个activity界面上的开关来控制悬浮窗的显示/隐藏/移除
这里 我们简化步骤 仅用activity来控制悬浮窗
1.首先是悬浮窗的布局(这里我们做一个时钟的悬浮窗)
floating_window.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="@android:color/holo_purple"
android:orientation="vertical" >
<DigitalClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="12sp"
android:background="@android:color/background_light"
android:alpha="0.8"/>
<AnalogClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light" />
</LinearLayout>
2.然后是activity的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.demo_xuanfuchuang.MainActivity" >
<!-- <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center" >
<!--这里我们使用两个button来控制悬浮窗显示/隐藏-->
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@android:color/holo_blue_light"
android:text="@string/action_start" />
<Button
android:id="@+id/end"
android:layout_width="wrap_content"