参考资源: android中的坐标系以及获取坐标的方法
效果图如下图所示:
未完成部分:
- 按钮会滑动到虚拟导航键盘下面,不知道哪出了问题: 模拟器问题,真机上莫得这个问题
public class MyFloatBtn extends FloatingActionButton {
private static final String TAG = "MyFloatBtn";
private int mLastX, mLastY;
private int mDownX, mDownY;
private int mScreenWidth, mScreenHeight;
public MyFloatBtn(Context context) {
super(context);
initData(context);
}
public MyFloatBtn(Context context, AttributeSet attrs) {
super(context, attrs);
initData(context);
}
public MyFloatBtn(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData(context);
}
private void initData(Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mScreenHeight = metrics.heightPixels;
mScreenWidth = metrics.widthPixels;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent ev) {
int actionId = ev.getAction();
switch (actionId) {
case MotionEvent.ACTION_DOWN:
mLastX = (int) ev.getRawX();
mLastY = (int) ev.getRawY();
mDownX = mLastX;
mDownY = mLastY;
break;
case MotionEvent.ACTION_UP:
if (calculateDistance(mDownX, mDownY, (int) ev.getRawX(), (int) ev.getRawY()) <= 5) {
Log.i(TAG, "onTouchEvent: 点击事件");
} else {
Log.i(TAG, "onTouchEvent: 拖动事件");
return true;
}
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) ev.getRawX() - mLastX;
int dy = (int) ev.getRawY() - mLastY;
int left = getLeft() + dx;
int top = getTop() + dy;
int right = getRight() + dx;
int bottom = getBottom() + dy;
mLastX = (int) ev.getRawX();
mLastY = (int) ev.getRawY();
if (top < 0) {
top = 0;
bottom = getHeight();
}
if (left < 0) {
left = 0;
right = getWidth();
}
if (bottom > mScreenHeight) {
bottom = mScreenHeight;
top = bottom - getHeight();
}
if (right > mScreenWidth) {
right = mScreenWidth;
left = right - getWidth();
}
layout(left, top, right, bottom);
break;
default:
break;
}
return super.onTouchEvent(ev);
}
private int calculateDistance(int downX, int downY, int lastX, int lastY) {
return (int) Math.sqrt(Math.pow(1.0f * (lastX - downX), 2.0) + Math.pow((lastY - downY) * 1.0f, 2.0));
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<work.wxmx.floatbtntest.MyFloatBtn
android:src="@drawable/ic_baseline_archive_24"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
|