Android 全局悬浮框(可拖动)

Android 悬浮框

效果图:
在这里插入图片描述
代码实现:

  1. Androidmanifest.xml添加弹框权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  1. 自定义悬浮窗类FloatWindow.java
public class FloatWindow implements View.OnTouchListener {

    private Context mContext;
    private WindowManager.LayoutParams mWindowParams;
    private WindowManager mWindowManager;

    private View mFloatLayout;
    private float mInViewX;
    private float mInViewY;
    private float mDownInScreenX;
    private float mDownInScreenY;
    private float mInScreenX;
    private float mInScreenY;
    private TextView infoText;

    public FloatWindow(Context context) {
        this.mContext = context;
        initFloatWindow();
    }

    private void initFloatWindow() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        if(inflater == null)
            return;
        mFloatLayout = (View) inflater.inflate(R.layout.layout_float, null);
        infoText = mFloatLayout.findViewById(R.id.textView);
        mFloatLayout.setOnTouchListener(this);

        mWindowParams = new WindowManager.LayoutParams();
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {//8.0新特性
            mWindowParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else{
            mWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        mWindowParams.format = PixelFormat.RGBA_8888;
        mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mWindowParams.gravity = Gravity.START | Gravity.TOP;
        mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return floatLayoutTouch(motionEvent);
    }

    private boolean floatLayoutTouch(MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 获取相对View的坐标,即以此View左上角为原点
                mInViewX = motionEvent.getX();
                mInViewY = motionEvent.getY();
                // 获取相对屏幕的坐标,即以屏幕左上角为原点
                mDownInScreenX = motionEvent.getRawX();
                mDownInScreenY = motionEvent.getRawY() - getSysBarHeight(mContext);
                mInScreenX = motionEvent.getRawX();
                mInScreenY = motionEvent.getRawY() - getSysBarHeight(mContext);
                break;
            case MotionEvent.ACTION_MOVE:
                // 更新浮动窗口位置参数
                mInScreenX = motionEvent.getRawX();
                mInScreenY = motionEvent.getRawY() - getSysBarHeight(mContext);
                mWindowParams.x = (int) (mInScreenX- mInViewX);
                mWindowParams.y = (int) (mInScreenY - mInViewY);
                // 手指移动的时候更新小悬浮窗的位置
                mWindowManager.updateViewLayout(mFloatLayout, mWindowParams);
                break;
            case MotionEvent.ACTION_UP:
                // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
                if (mDownInScreenX  == mInScreenX && mDownInScreenY == mInScreenY){

                }
                break;
        }
        return true;
    }

    public void showFloatWindow(){
        if (mFloatLayout.getParent() == null){
            DisplayMetrics metrics = new DisplayMetrics();
            // 默认固定位置,靠屏幕右边缘的中间
            mWindowManager.getDefaultDisplay().getMetrics(metrics);
            mWindowParams.x = metrics.widthPixels;
            mWindowParams.y = metrics.heightPixels/2 - getSysBarHeight(mContext);
            mWindowManager.addView(mFloatLayout, mWindowParams);
        }
    }

    public void updateText(final String s) {
        infoText.setText(s);
    }

    public void hideFloatWindow(){
        if (mFloatLayout.getParent() != null)
            mWindowManager.removeView(mFloatLayout);
    }

    public void setFloatLayoutAlpha(boolean alpha){
        if (alpha)
            mFloatLayout.setAlpha((float) 0.5);
        else
            mFloatLayout.setAlpha(1);
    }

    // 获取系统状态栏高度
    public static int getSysBarHeight(Context contex) {
        Class<?> c;
        Object obj;
        Field field;
        int x;
        int sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = contex.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }
}
  1. 自定义悬浮窗界面布局文件layout_float.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/float_win"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ffffff"
        android:text="hello"
        android:textSize="12sp"
        app:layout_constraintLeft_toLeftOf="@id/imageView"
        app:layout_constraintRight_toRightOf="@id/imageView"
        app:layout_constraintTop_toBottomOf="@id/imageView"/>

</android.support.constraint.ConstraintLayout>
  1. 在Activity中使用悬浮窗。
public class MainActivity extends AppCompatActivity {

    private Button btnShow;
    FloatWindow floatWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 权限判断
        if (Build.VERSION.SDK_INT >= 23) {
            if(!Settings.canDrawOverlays(getApplicationContext())) {
                // 启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,10);
            } else {
                // 执行6.0以上绘制代码
                initView();
            }
        } else {
            // 执行6.0以下绘制代码
            initView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 权限判断
        if (Build.VERSION.SDK_INT >= 23) {
            if(Settings.canDrawOverlays(getApplicationContext())) {
                initView();
            }
        } else {
            //执行6.0以下绘制代码
            initView();
        }
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        floatWindow = new FloatWindow(getApplicationContext());

        btnShow = findViewById(R.id.btn_show);
        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != floatWindow) {
                    floatWindow.showFloatWindow();
                }
            }
        });

        Button btnrefresh = findViewById(R.id.btn_refresh);
        btnrefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int random = (int) (Math.random() * 10);
                if (null != floatWindow) {
                    floatWindow.updateText(String.valueOf(random));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != floatWindow) {
            floatWindow.hideFloatWindow();
        }
    }
}
  • 12
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Android全局拖动悬浮按钮是一种在应用界面上悬浮的按钮,用户可以通过拖动按钮的方式,在任意界面使用其提供的功能。这种悬浮按钮通常会呈现在屏幕的某个固定位置,如屏幕右下角。 使用全局拖动悬浮按钮可以为用户提供方便和快捷的操作方式。用户只需通过轻触按钮即可快速打开某个应用或执行某个功能,而不需要返回主界面或搜索相应的功能选项。这样可以大大提高用户的操作效率和体验。 开发这一功能的关键在于如何实现悬浮按钮在全局范围内的拖动和点击事件。一种常用的方法是通过在Android系统的WindowManager中创建一个可拖动的View,并设置其触摸事件监听器来实现。在触摸事件监听器中,我们可以处理按钮的拖动、点击、长按等各种事件。 为了使全局拖动悬浮按钮更好地融入应用界面,我们可以对其进行自定义设置。例如,可以自定义按钮的形状、颜色、动画效果等,以适配不同的应用主题和风格。 需要注意的是,在设计和使用全局拖动悬浮按钮时,我们要遵循用户界面设计的基本原则,避免对用户的正常操作造成干扰和困扰。同时,也要考虑到移动设备的屏幕尺寸和分辨率的差异,以确保全局拖动悬浮按钮在不同设备上都能够正常显示和操作。 总而言之,Android全局拖动悬浮按钮是一种方便用户操作的功能,通过简单轻松的拖动和点击,用户可以快速访问应用的各种功能。开发者可以根据应用的需求和用户体验考虑,来设计和实现这一功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值