简单的代码快速创建悬浮窗

1
2
3
4
5
6
7
8
9
10
11
12
13
WindowManager mWindowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams mWindowParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_TOAST,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,//不接受事件及触摸
PixelFormat.RGBA_8888);
if (Build.VERSION.SDK_INT < 19 ) {
mWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}else{
mWindowParams.type = WindowManager.LayoutParams.TYPE_TOAST;
}
mWindowManager.addView(new DesktopLayout(context),mWindowParams );
  • DesktopLayout
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class DesktopLayout extends LinearLayout {
    public DesktopLayout(Context context) {
    super(context);
    setOrientation(LinearLayout.VERTICAL);// 水平排列
    //设置宽高
    this.setLayoutParams( new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT));

    View view = LayoutInflater.from(context).inflate(
    R.layout.desklayout, null);
    this.addView(view);
    }
    }
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100px"
    android:layout_height="100px"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="100px"
        android:layout_height="100px"
        android:text="测试"/>
</LinearLayout>
``` xml