最近遇到有需要实现拖拽功能的控件,之前也写过,只是没有做记录就需要重做,所以这次顺便记录一下,以后直接复制粘贴岂不快哉?!
![demo.jpg](https://i-blog.csdnimg.cn/blog_migrate/cd9a3620c1b6fb0211210c88aaeb617a.gif)
1. 主要思路
主要通过设置 View 的 OnTouchListener 达到监控拖拽信息的效果。根据 touch 事件的坐标信息变化控制控件的位置,这里使用的是 setTranslationX 与 setTranslationY 来改变 View 在屏幕上显示的位置,计算之后设定偏移即可。对于 touch 事件中坐标信息不熟悉的同学可以看一下这篇文章:Android View获取坐标值、相对距离的方法。
2. 代码
package com.dongmodao.alpha;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class DragTouchListener implements View.OnTouchListener {
@IntDef({
HORIZONTAL, VERTICAL, FREE})
@Retention(RetentionPolicy.SOURCE)
private @interface OrientationMode {
}
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int FREE = 2;
private float curX;
private float curY;
private float startX;
private float startY;
private float tranX;
private float tranY;
private int direct = FREE;
private final View view;
private OnDragListener listener;
private</