溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Android中實現(xiàn)一個懸浮按鈕

發(fā)布時間:2020-11-27 16:31:39 來源:億速云 閱讀:181 作者:Leah 欄目:移動開發(fā)

怎么在Android中實現(xiàn)一個懸浮按鈕?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

具體實現(xiàn)代碼:

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; //懸浮按鈕點擊回調(diào)

  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();
    //獲取到狀態(tài)欄的高度
    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) {//屏幕旋轉(zhuǎn)切換
      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, "執(zhí)行點擊事件");
    if (!isFirstClick) {
      OpenIDApplication.getInstance().floatBtnClick(context, OpenIDApplication.getInstance().isForceLogin(), resultCallback);
    } else {//半隱藏狀態(tài),點擊顯示全部
      isFirstClick = false;
      showAllBtn();
    }
  }

}

調(diào)用實現(xiàn)代碼,這里注意有個問題,彈出系統(tǒng)級的懸浮窗,需要配置權限:

并且Android 6.0以上的手機,還要彈出對話框問用戶是否運行,如果這個用戶拒絕了,就不能彈出系統(tǒng)級的懸浮窗了,還有個別手機廠商修改了android源碼,還需要進系統(tǒng)設置里去允許這個應用彈出懸浮窗。這樣的話就體驗感非常不好,不過這里有個小技巧,按下面方式設置為toast類型就完全解決,既不用配置權限,也不彈出窗來向用戶獲取權限,完全解決問題。

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

具體實現(xiàn)代碼如下:

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

   WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
   // 設置LayoutParams(全局變量)相關參數(shù)
   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 不可觸摸
    */
   // 調(diào)整懸浮窗口至左上角,便于調(diào)整坐標
   windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP;
   // 以屏幕左上角為原點,設置x、y初始值
   windowManagerParams.x = 0;
   windowManagerParams.y = 0;
   // 設置懸浮窗口長寬數(shù)據(jù)
   floatBtn.measure(0, 0);
   floatBtn.setOriginWidth(floatBtn.getMeasuredWidth() - 50);
   windowManagerParams.width = floatBtn.getOriginWidth();
   windowManagerParams.height = windowManagerParams.width;
   // 顯示myFloatView圖像
   windowManager.addView(floatBtn, windowManagerParams);

關于怎么在Android中實現(xiàn)一個懸浮按鈕問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI