Android activity内实现可拖拽悬浮控件
Posted 猫叔聊技术
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android activity内实现可拖拽悬浮控件相关的知识,希望对你有一定的参考价值。
效果图
实现方式:
//在activity中重写此方法
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState)
super.onPostCreate(savedInstanceState);
//添加一个悬浮
View root = findViewById(android.R.id.content);
if (root instanceof FrameLayout)
FrameLayout content = (FrameLayout) root;
ImageView stackView = new ImageView(this);
stackView.setImageResource(R.drawable.fragmentation_ic_stack);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.END;
int dp18 = SizeUtils.dp2px(18);
params.topMargin = dp18 * 7;
params.rightMargin = dp18;
stackView.setLayoutParams(params);
content.addView(stackView);
stackView.setOnTouchListener(new StackViewTouchListener(stackView, dp18 / 4));
stackView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
ToastUtils.showLong("现在是点击的时候哦");
);
2.自定义触摸事件
package com.xh2015.sdk.sdktest.listener;
import android.view.MotionEvent;
import android.view.View;
/**
* Author:gary
* <p/>
* Email: xuhaozv@163.com
* <p/>
* description:
* <p/>
* Date: 2020-12-02 18:13
*/
public class StackViewTouchListener implements View.OnTouchListener
private View stackView;
private float dx, dy = 0F;
private float downX, downY = 0F;
private boolean isClickState;
private int clickLimitValue;
public StackViewTouchListener(View stackView, int clickLimitValue)
this.stackView = stackView;
this.clickLimitValue = clickLimitValue;
@Override
public boolean onTouch(View v, MotionEvent event)
float X = event.getRawX();
float Y = event.getY();
switch (event.getAction())
case MotionEvent.ACTION_DOWN:
isClickState = true;
downX = X;
downY = Y;
System.out.println(v.toString());
System.out.println(stackView.toString());
dx = stackView.getX() - event.getRawX();
dy = stackView.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
if (Math.abs(X - downX) < clickLimitValue && Math.abs(Y - downY) < clickLimitValue)
isClickState = true;
else
isClickState = false;
stackView.setX(event.getRawX() + dx);
stackView.setY(event.getRawY() + dy);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isClickState)
stackView.performClick();
break;
default:
return false;
return true;
以上是关于Android activity内实现可拖拽悬浮控件的主要内容,如果未能解决你的问题,请参考以下文章
android可拖拽悬浮控件和Kotlin的可拖拽悬浮控件/可拖拽悬浮按钮带Demo附件