欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android 实现可任意拖动的悬浮窗功能(类似悬浮球)

程序员文章站 2022-03-11 23:00:07
最近开发项目中,有个在屏幕上任意拖动的悬浮窗功能,其实就是利用 windowmanager的api来完成这个需求,具体的实现的功能如下:1.自定义viewimport android.content....

最近开发项目中,有个在屏幕上任意拖动的悬浮窗功能,其实就是利用 windowmanager的api来完成这个需求,具体的实现的功能如下:
1.自定义view

import android.content.context;
import android.content.intent;
import android.os.handler;
import android.os.message;
import android.util.log;
import android.util.typedvalue;
import android.view.motionevent;
import android.view.view;
import android.view.viewconfiguration;
import android.view.windowmanager;
import android.widget.linearlayout;
import com.xinrui.recordscreen.r;
import java.lang.reflect.field;
/**
 *
 */
public class recordscreenview extends linearlayout implements view.onclicklistener{
  private windowmanager mwindowmanager;
  private windowmanager.layoutparams mlayoutparams;
  private long mlastdowntime;
  private float mlastdownx;
  private float mlastdowny;
  private boolean mislongtouch;
  private boolean mistouching;
  private float mtouchslop;
  private final static long long_click_limit = 20;
  private final static int time_count = 0;
  private int mstatusbarheight;
  private int mcurrentmode,time=0;
  private final static int mode_none = 0x000;
  private final static int mode_move = 0x001;
  private int moffsettoparent;
  private int moffsettoparenty;
  private context mcontext;
  public recordscreenview(context context) {
    super(context);
    this.mcontext=context;
    mwindowmanager = (windowmanager) getcontext().getsystemservice(context.window_service);
    initview();
  }
  private void initview() {
    view view = inflate(getcontext(), r.layout.layout_ball, this);
    mtouchslop = viewconfiguration.get(getcontext()).getscaledtouchslop();
    mcurrentmode = mode_none;
    recordtime(0);
    mstatusbarheight = getstatusbarheight();
    moffsettoparent = dip2px(25);
    moffsettoparenty = mstatusbarheight + moffsettoparent;
    view.setontouchlistener(new ontouchlistener() {
      @override
      public boolean ontouch(view v, final motionevent event) {
        switch (event.getaction()) {
          case motionevent.action_down:
            mistouching = true;
            mlastdowntime = system.currenttimemillis();
            mlastdownx = event.getx();
            mlastdowny = event.gety();
            postdelayed(new runnable() {
              @override
              public void run() {
                if (islongtouch()) {
                  mislongtouch = true;
                }
              }
            }, long_click_limit);
            break;
          case motionevent.action_move:
            if (!mislongtouch && istouchslop(event)) {
              return true;
            }
            if (mislongtouch && (mcurrentmode == mode_none || mcurrentmode == mode_move)) {
              mlayoutparams.x = (int) (event.getrawx() - moffsettoparent);
              mlayoutparams.y = (int) (event.getrawy() - moffsettoparenty);
              mwindowmanager.updateviewlayout(recordscreenview.this, mlayoutparams);//不断刷新悬浮窗的位置
              mcurrentmode = mode_move;
            }
            break;
          case motionevent.action_cancel:
          case motionevent.action_up:
            mistouching = false;
            if (mislongtouch) {
              mislongtouch = false;
            }
            mcurrentmode = mode_none;
            break;
        }
        return true;
      }
    });
  }
  private boolean islongtouch() {
    long time = system.currenttimemillis();
    if (mistouching && mcurrentmode == mode_none && (time - mlastdowntime >= long_click_limit)) {
      return true;
    }
    return false;
  }
  /**
   * 判断是否是轻微滑动
   *
   * @param event
   * @return
   */
  private boolean istouchslop(motionevent event) {
    float x = event.getx();
    float y = event.gety();
    if (math.abs(x - mlastdownx) < mtouchslop && math.abs(y - mlastdowny) < mtouchslop) {
      return true;
    }
    return false;
  }
  public void setlayoutparams(windowmanager.layoutparams params) {
    mlayoutparams = params;
  }
  /**
   * 获取通知栏高度
   *
   * @return
   */
  private int getstatusbarheight() {
    int statusbarheight = 0;
    try {
      class<?> c = class.forname("com.android.internal.r$dimen");
      object o = c.newinstance();
      field field = c.getfield("status_bar_height");
      int x = (integer) field.get(o);
      statusbarheight = getresources().getdimensionpixelsize(x);
    } catch (exception e) {
      e.printstacktrace();
    }
    return statusbarheight;
  }
  public int dip2px(float dip) {
    return (int) typedvalue.applydimension(
        typedvalue.complex_unit_dip, dip, getcontext().getresources().getdisplaymetrics()
    );
  }
}

2.添加windowmanager添加view

import android.content.context;
import android.graphics.pixelformat;
import android.view.gravity;
import android.view.windowmanager;
import android.view.windowmanager.layoutparams;

/**
 * created by wangxiandeng on 2016/11/25.
 */

public class floatwindowmanager {
  private static recordscreenview mballview;

  private static windowmanager mwindowmanager;


  public static void addballview(context context) {
    if (mballview == null) {
      windowmanager windowmanager = getwindowmanager(context);
      int screenwidth = windowmanager.getdefaultdisplay().getwidth();
      int screenheight = windowmanager.getdefaultdisplay().getheight();
      mballview = new recordscreenview(context);
      layoutparams params = new layoutparams();
      params.x = screenwidth/2;
      params.y = screenheight/2+150;
      params.width = layoutparams.wrap_content;
      params.height = layoutparams.wrap_content;
      params.gravity = gravity.left | gravity.top;
      params.type = layoutparams.type_application_overlay;
      params.format = pixelformat.rgba_8888;
      params.flags = layoutparams.flag_not_touch_modal
          | layoutparams.flag_not_focusable;
      mballview.setlayoutparams(params);
      windowmanager.addview(mballview, params);
    }
  }

  public static void removeballview(context context) {
    if (mballview != null) {
      windowmanager windowmanager = getwindowmanager(context);
      windowmanager.removeview(mballview);
      mballview = null;
    }
  }

  private static windowmanager getwindowmanager(context context) {
    if (mwindowmanager == null) {
      mwindowmanager = (windowmanager) context.getsystemservice(context.window_service);
    }
    return mwindowmanager;
  }
}

3.acitivity中调用

import android.app.activity;
import android.content.intent;
import android.os.build;
import android.os.bundle;
import android.provider.settings;
import android.util.log;
import android.widget.toast;

import com.xinrui.recordscreen.view.floatwindowmanager;

public class mainactivity extends activity {

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    if (build.version.sdk_int >= 23) {
    //设置中请求开启悬浮窗权限
      if (!settings.candrawoverlays(this)) {
        intent intent = new intent(settings.action_manage_overlay_permission);
        intent.addflags(intent.flag_activity_new_task);
        startactivity(intent);
        toast.maketext(this, mainactivity.this.getresources().getstring(r.string.open_float), toast.length_short).show();
      }else{
        initview();
      }
    }
  }

  private void initview() {
    floatwindowmanager.addballview(mainactivity.this);
    finish();
  }
}

5.androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.xinrui.recordscreen">
  <uses-permission android:name="android.permission.internet"/>
  <uses-permission android:name="android.permission.read_external_storage"/>
  <uses-permission android:name="android.permission.write_external_storage"/>
  <uses-permission android:name="android.permission.system_alert_window"/>//悬浮窗权限
  <application
    android:allowbackup="true"
    android:icon="@drawable/recording_screen_nor"
    android:label="@string/app_name"
    android:supportsrtl="true">
    <activity android:name="com.xinrui.recordscreen.mainactivity">
      <intent-filter>
        <action android:name="android.intent.action.main" />

        <category android:name="android.intent.category.launcher" />
      </intent-filter>
    </activity>
</manifest>

总结

到此这篇关于android 实现可任意拖动的悬浮窗功能(类似悬浮球)的文章就介绍到这了,更多相关android任意拖动的悬浮窗内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: android 悬浮窗