全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Android实现系统级悬浮按钮

本文实例为大家分享了Android系统级悬浮按钮的具体代码,供大家参考,具体内容如下

具体的需求

1、就是做一个系统级的悬浮按钮,就像iPhone 桌面的那个悬浮按钮效果一样,能随意拖动,并且手一放开,悬浮按钮就自动靠边。
2、可以点击并且可以随意拖动。
3、悬浮按钮自动靠边的时候,或者移动到边上的时候,自动隐藏半边。
4、横竖屏切换都兼容

1、就在WindowManager 里面添加View,这个View通过自定义控件来实现。
2、在onTouch里的MotionEvent.ACTION_MOVE事件里头,通过控制悬浮按钮的具体坐标来实现随意移动。
3、在onTouch里的MotionEvent.ACTION_UP事件里头,来控制悬浮按钮自动靠边,并且自动隐藏半边,不过在这里onTouch和onClick这两个事件是一起触发的,不过这也有解决办法,你可以在手放开的瞬间,通过移动的距离,来决定是否触发点击事件,,如果返回false,就会触发点击事件,如果返回true就会触发点击事件
4、通过自定义控件onLayout方法,来捕获横竖屏切换事件,
5、还有一个靠哪边停靠的问题,通过坐标来判读更靠近哪一边。就靠哪边停靠。
![以中间这个中心点为准,以更短的X轴画一个正方形]

下面是具体实现代码:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.iapppay.openid.channel.LoginResultCallback;
import com.iapppay.openid.channel.OpenIDApplication;
import com.iapppay.openid.channel.util.DisplayUtil;
import com.iapppay.openid.channel.util.LogUtil;
import com.iapppay.openid.channel.util.Res;

/**
 * Created by HuangTiebing 2017/2/14.
 */

public class DragFloatActionButton extends ImageView implements View.OnTouchListener, View.OnClickListener {

  public static String TAG = "DragFloatActionButton";
  private Context context;

  float lastX, lastY;
  float originX, originY;
  int screenWidth;
  int screenHeight;
  private int originWidth;

  private WindowManager windowManager;
  //  // 此windowManagerParams变量为获取的全局变量,用以保存悬浮窗口的属性
  private WindowManager.LayoutParams windowManagerParams;

  private LoginResultCallback resultCallback; //悬浮按钮点击回调

  public DragFloatActionButton(Context context, boolean isForceLogin, LoginResultCallback resultCallback) {
    this(context, null);
    OpenIDApplication.getInstance().setForceLogin(isForceLogin);
    this.resultCallback = resultCallback;
  }

  public DragFloatActionButton(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public DragFloatActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.context = context;

    Point screenSize = DisplayUtil.getScreenSize(context);
    screenWidth = screenSize.x;
    screenHeight = screenSize.y;
    setImageResource(Res.drawable(context, "ipay_float_btn_bg"));
    setOnTouchListener(this);
    setOnClickListener(this);

    windowManager = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
  }

  public int getOriginWidth() {
    return originWidth;
  }

  public void setOriginWidth(int originWidth) {
    this.originWidth = originWidth;
  }

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    windowManagerParams = (WindowManager.LayoutParams) this.getLayoutParams();
    //获取到状态栏的高度
    Rect frame = new Rect();
    getWindowVisibleDisplayFrame(frame);
    int ea = event.getAction();
    switch (ea) {
      case MotionEvent.ACTION_DOWN:
        lastX = event.getRawX();// 获取触摸事件触摸位置的原始X坐标
        lastY = event.getRawY();
        originX = lastX;
        originY = lastY;
        break;
      case MotionEvent.ACTION_MOVE:
        float dx = event.getRawX() - lastX;
        float dy = event.getRawY() - lastY;
        windowManagerParams.x += dx;
        windowManagerParams.y += dy;
        LogUtil.d(TAG, "移动距离:dx=" + dx + ",dy=" + dy);
        showAllBtn();
        lastX = (int) event.getRawX();
        lastY = (int) event.getRawY();
        break;
      case MotionEvent.ACTION_UP:
        float lastMoveDx = Math.abs(event.getRawX() - originX);
        float lastMoveDy = Math.abs(event.getRawY() - originY);
        LogUtil.d(TAG, "松开时,移动距离:lastMoveDx=" + lastMoveDx + ", lastMoveDy=" + lastMoveDy);
        if (lastMoveDx < 10 && lastMoveDy < 10) { //移动距离太小,视为点击,
          return false;
        } else {
          updateViewLayout(event);
          isFirstClick = true;
          return true;
        }
    }
    return false;
  }

  /**
   * 显示整个图标
   */
  public void showAllBtn() {
    windowManagerParams.width = originWidth;
    windowManagerParams.height = originWidth;
    setImageResource(Res.drawable(context, "ipay_float_btn_bg"));
    windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
  }

  /**
   * 悬浮按钮显示在左边
   */
  private void showInLeft() {
    windowManagerParams.x = 0;
    windowManagerParams.width = originWidth / 2;
    windowManagerParams.height = originWidth;
    setImageResource(Res.drawable(context, "ipay_float_btn_left_hidden"));
    windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
  }

  /**
   * 悬浮按钮显示在右边
   */
  private void showInRight() {
    windowManagerParams.width = originWidth / 2;
    windowManagerParams.height = originWidth;
    windowManagerParams.x = screenWidth - windowManagerParams.width;
    setImageResource(Res.drawable(context, "ipay_float_btn_right_hidden"));
    windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
  }

  /**
   * 悬浮按钮显示在上面
   */
  private void showInTop() {
    windowManagerParams.y = 0;
    windowManagerParams.width = originWidth;
    windowManagerParams.height = originWidth / 2;
    setImageResource(Res.drawable(context, "ipay_float_btn_top_hidden"));
    windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
  }

  /**
   * 悬浮按钮显示在下面
   */
  private void showInBottom() {
    windowManagerParams.width = originWidth;
    windowManagerParams.height = originWidth / 2;
    windowManagerParams.y = screenHeight - windowManagerParams.width;
    setImageResource(Res.drawable(context, "ipay_float_btn_bottom_hidden"));
    windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示
  }

  /**
   * 更新悬浮图标
   *
   * @param event 手动移动事件
   */
  public void updateViewLayout(MotionEvent event) {
    Point center = new Point(screenWidth / 2, screenHeight / 2); //屏幕中心点
    float xOffset, yOffset;//以屏幕中心点为原点,X轴和Y轴上的偏移量
    if (event != null) {//手动移动的
      xOffset = event.getRawX() - center.x;
      yOffset = event.getRawY() - center.y;
    } else {//自动隐藏
      xOffset = lastX - center.x;
      yOffset = lastY - center.y;
    }
    if (Math.abs(xOffset) >= Math.abs(yOffset)) {//向左或向右缩进隐藏
      if (xOffset <= 0) { //向左缩进
        showInLeft();
      } else {
        showInRight();
      }
    } else {//向上或向下缩进隐藏
      if (yOffset <= 0) {//向上缩进
        showInTop();
      } else {
        showInBottom();
      }
    }
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }

  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    Point screenSize = DisplayUtil.getScreenSize(context);
    if (screenWidth != screenSize.x) {//屏幕旋转切换
      screenWidth = screenSize.x;
      screenHeight = screenSize.y;
      lastY = windowManagerParams.x;
      lastX = windowManagerParams.y;
      windowManagerParams.x = (int) lastX;
      windowManagerParams.y = (int) lastY;
      updateViewLayout(null);
    }
  }

  private boolean isFirstClick = true;

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
  }

  @Override
  public void onClick(View v) {
    LogUtil.d(TAG, "执行点击事件");
    if (!isFirstClick) {
      OpenIDApplication.getInstance().floatBtnClick(context, OpenIDApplication.getInstance().isForceLogin(), resultCallback);
    } else {//半隐藏状态,点击显示全部
      isFirstClick = false;
      showAllBtn();
    }
  }

}

调用实现代码,这里注意有个问题,弹出系统级的悬浮窗,需要配置权限:

并且Android 6.0以上的手机,还要弹出对话框问用户是否运行,如果这个用户拒绝了,就不能弹出系统级的悬浮窗了,还有个别手机厂商修改了android源码,还需要进系统设置里去允许这个应用弹出悬浮窗。这样的话就体验感非常不好,不过这里有个小技巧,按下面方式设置为toast类型就完全解决,既不用配置权限,也不弹出窗来向用户获取权限,完全解决问题。

WindowManager.LayoutParams windowManagerParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST, 
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, 
PixelFormat.TRANSLUCENT);

具体实现代码如下:

DragFloatActionButton floatBtn = new DragFloatActionButton(context, isForceLogin, mResultCallback);

   WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
   // 设置LayoutParams(全局变量)相关参数
   WindowManager.LayoutParams windowManagerParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST,
     WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
     PixelFormat.TRANSLUCENT);
   /**
    * 注意,flag的值可以为:
    * 下面的flags属性的效果形同“锁定”。
    * 悬浮窗不可触摸,不接受任何事件,同时不影响后面的事件响应。
    * LayoutParams.FLAG_NOT_TOUCH_MODAL 不影响后面的事件
    * LayoutParams.FLAG_NOT_FOCUSABLE 不可聚焦
    * LayoutParams.FLAG_NOT_TOUCHABLE 不可触摸
    */
   // 调整悬浮窗口至左上角,便于调整坐标
   windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP;
   // 以屏幕左上角为原点,设置x、y初始值
   windowManagerParams.x = 0;
   windowManagerParams.y = 0;
   // 设置悬浮窗口长宽数据
   floatBtn.measure(0, 0);
   floatBtn.setOriginWidth(floatBtn.getMeasuredWidth() - 50);
   windowManagerParams.width = floatBtn.getOriginWidth();
   windowManagerParams.height = windowManagerParams.width;
   // 显示myFloatView图像
   windowManager.addView(floatBtn, windowManagerParams);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Android  # 悬浮按钮  # Android开发悬浮按钮 Floating ActionButton的实现方法  # Android仿知乎悬浮功能按钮FloatingActionButton效果  # Android自定义可拖拽的悬浮按钮DragFloatingActionButton  # Android开发之FloatingActionButton悬浮按钮基本使用、字体、颜色用法示例  # android 应用内部悬浮可拖动按钮简单实现代码  # Android悬浮按钮的使用方法  # Android悬浮窗按钮实现点击并显示/隐藏多功能列表  # Android自定义APP全局悬浮按钮  # Android利用WindowManager生成悬浮按钮及悬浮菜单  # Android自定义悬浮按钮效果  # 弹出  # 就会  # 有个  # 中心点  # 自定义  # 拖动  # 来实现  # 全局变量  # 也不  # 在这里  # 就在  # 就像  # 你可以  # 这也  # 这两个  # 还有一个  # 做一个  # 就不能  # 解决问题  # 还需要 


相关文章: 专业网站制作服务公司,有哪些网站可以免费发布招聘信息?  制作网站的模板软件,网站怎么建设?  实现点击下箭头变上箭头来回切换的两种方法【推荐】  建站之星伪静态规则如何正确配置?  建站主机选哪种环境更利于SEO优化?  建站之星体验版:智能建站系统+响应式设计,多端适配快速建站  XML的“混合内容”是什么 怎么用DTD或XSD定义  建站之星Pro快速搭建教程:模板选择与功能配置指南  建站之星与建站宝盒如何选择最佳方案?  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  潍坊网站制作公司有哪些,潍坊哪家招聘网站好?  正规网站制作公司有哪些,目前国内哪家网页网站制作设计公司比较专业靠谱?口碑好?  金*站制作公司有哪些,金华教育集团官网?  如何在阿里云购买域名并搭建网站?  Android自定义listview布局实现上拉加载下拉刷新功能  制作网站哪家好,cc、.co、.cm哪个域名更适合做网站?  网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?  c# 服务器GC和工作站GC的区别和设置  如何通过万网虚拟主机快速搭建网站?  网站制作怎么样才能赚钱,用自己的电脑做服务器架设网站有什么利弊,能赚钱吗?  想学网站制作怎么学,建立一个网站要花费多少?  宝塔建站教程:一键部署配置流程与SEO优化实战指南  小自动建站系统:AI智能生成+拖拽模板,多端适配一键搭建  小说建站VPS选用指南:性能对比、配置优化与建站方案解析  台州网站建设制作公司,浙江手机无犯罪记录证明怎么开?  上海网站制作开发公司,上海买房比较好的网站有哪些?  如何通过虚拟主机空间快速建站?  建站之星官网登录失败?如何快速解决?  教学论文网站制作软件有哪些,写论文用什么软件 ?  如何用虚拟主机快速搭建网站?详细步骤解析  如何快速搭建高效可靠的建站解决方案?  建站之星导航配置指南:自助建站与SEO优化全解析  佛山网站制作系统,佛山企业变更地址网上办理步骤?  建站主机是什么?如何选择适合的建站主机?  建站之星×万网:智能建站系统+自助建站平台一键生成  html制作网站的步骤有哪些,iapp如何添加网页?  如何注册花生壳免费域名并搭建个人网站?  广州商城建站系统开发成本与周期如何控制?  建站之星展会模版如何一键下载生成?  如何在景安云服务器上绑定域名并配置虚拟主机?  建站之星安装后界面空白如何解决?  如何选择建站程序?包含哪些必备功能与类型?  魔方云NAT建站如何实现端口转发?  建站10G流量真的够用吗?如何应对访问高峰?  如何在云指建站中生成FTP站点?  青岛网站设计制作公司,查询青岛招聘信息的网站有哪些?  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  重庆市网站制作公司,重庆招聘网站哪个好?  北京网页设计制作网站有哪些,继续教育自动播放怎么设置?  定制建站如何定义?其核心优势是什么? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。