安卓悬浮窗

本文介绍了一个用于创建Android浮动窗口的类FloatWindow。该类通过WindowManager实现了浮动窗口的创建、显示、隐藏及位置调整等功能,并提供了详细的参数配置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;



public class FloatWindow {

    private View view;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    //单例对象
    //private static  FloatWindow floatWindow;

    public FloatWindow(Context context, View view) {
        this.view = view;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        layoutParams = new WindowManager.LayoutParams();
        layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        layoutParams.format = PixelFormat.TRANSPARENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL 
            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.height = ScreenUtil.dp2px(200);
        layoutParams.width = ScreenUtil.getScreenWidth();
        layoutParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
    }

//    //单例模式,
//    public static FloatWindow getInstance(Context context, View view) {
//        if (floatWindow == null) {
//            synchronized (FloatService.class) {
//                if (floatWindow == null)
//                    return floatWindow = new FloatWindow(context, view);
//                else
//                    return floatWindow;
//            }
//        } else return floatWindow;
//    }

    //设置Flag
    public void setFlags(int flags) {
        layoutParams.flags = flags;
        update();
    }

    public void updateXY(int x, int y) {
        layoutParams.x += x;
        layoutParams.y += y;
        update();
    }

    public void setXY(int x, int y) {
        layoutParams.x = x;
        layoutParams.y = y;
        update();
    }

    //设置宽高,传入-1.则不修改
    public void setWH(int width, int height) {
        if (width != -1)
            layoutParams.width = width;
        if (height != -1)
            layoutParams.height = height;
        update();
    }

    //显示
    public void show() {
        if (!view.isShown()) {
            windowManager.addView(view, layoutParams);
        }
    }

    //移除
    public void remove() {
        if (view.isShown()) {
            windowManager.removeView(view);
        }
    }

    //更新
    public void update() {
        if (view.isShown())
            windowManager.updateViewLayout(view, layoutParams);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值